add unique constraint to input field angular form code example
Example: unique validator angular reactive form
// How to check for unique validity in MEAN stack apps
// Backend : Node + Express + MongoDB
// DB-backend communication : mongoose + mongoose_unique_validator
// Angular script to show validations errors in UI
// You have to match angular's formControlNames with mongoose's model fields
// Init
fg: FormGroup
constructor(private $http: HttpClient) {}
// your http request
this.$http.post('//my_post_url', data).subscribe(
(e) => {
console.log('All is well')
},
(error) => {
console.error('we got errors')
Object.keys(error.errors)
.map((errorKey) => errors[errorKey].path)
.forEach((path) => {
// path: name of mongoose schema field where unique error occured
this.fg.get(path).setErrors({ notUnique: true })
})
}
)