Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Custom validator always returns true, even when condition is false

Tags:

angular

I've written a custom validator for email addresses that looks like this:

function emailValidator(control: FormControl): { [s: string]: boolean } {
    if (!control.value.match(/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i)) {
      console.log('invalid');
      return {invalidEmail: true};
    }else{
      console.log('valid');
      return {invalidEmail: false};
    }
}

I'm using the validator to display a error message on my page with the following html:

   <div class="formError" *ngIf="myForm.controls['email'].hasError('invalidEmail')">
         <p>
            <i class="fa fa-exclamation-triangle"></i> Enter your email address.
        </p>
   </div>

My FormGroup looks like this:

this.myForm = fb.group({
  'content' : ['',Validators.minLength(10)],
  'email' : ['',Validators.compose([Validators.required,emailValidator])],
  'name' : ['',Validators.required],
  'captcha' : ['',this.captchaValidator(this.captchaA,this.captchaB)]
});

When I enter a invalid email address the error message is displaying as it should do. When i enter a valid email address the message is also showing. When a valid email address is entered the string "valid" is logged in my console which means that my emailValidator returns false and this should make the error message disappear. Any thought about what might be the problem?

like image 308
Jakob Svenningsson Avatar asked Oct 25 '25 05:10

Jakob Svenningsson


1 Answers

If your validation is successful, you need to return null and not an object:

function emailValidator(control: FormControl): { [s: string]: boolean } {
  if (!control.value.match(/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i)) {
    console.log('invalid');
    return {invalidEmail: true};
  } else {
    console.log('valid');
    return null; // <-------
  }
}
like image 99
Thierry Templier Avatar answered Oct 26 '25 20:10

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!