0
votes

I am new to Angular and am trying to unserstand basic form validation code. here the below checkValidEmail is trying to check if user input email is equal to [email protected]. What I am not understanding is when email is [email protected] why the form validation is false? For the full source code - https://stackblitz.com/edit/angular-p4bz6e?file=src%2Fapp%2Fapp.component.ts

checkValidEmail(control: AbstractControl) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (control.value === '[email protected]') {
            resolve({ test: false })
        } else {resolve(null)}
      }, 2000)
    })
2
In stackblitz you are returning as { emailIsTaken: true }. Do you want to succeed the validation only when [email protected] is given or the opposite.? - Laminoo Lawrance

2 Answers

1
votes

The form validation will fail because in abstract control or user defined validation checkValidEmail you are returning { emailIsTaken: true }. so any response returned from custom validation will be added emailcontrol error property.

hence form get invalid due to the error added from abstract control defined.

Try printing it in the app.component.html as below.

<p> Form emailIsTaken {{form.controls.email.errors | json}}</p>
0
votes

Just change the condition in your custom validation and try the logic,

checkValidEmail(control: AbstractControl) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (control.value !== '[email protected]') {
        resolve({ emailIsTaken: true })
      } else {resolve(null)}
    }, 2000)
  })