Skip to content

Instantly share code, notes, and snippets.

@javebratt
Last active September 1, 2017 11:24
Show Gist options
  • Save javebratt/2fdd968e3f3c92886a34d1159bd4c09e to your computer and use it in GitHub Desktop.
Save javebratt/2fdd968e3f3c92886a34d1159bd4c09e to your computer and use it in GitHub Desktop.
Email Validator what works for NG2 and Ionic 2 apps.
import {FormControl} from '@angular/forms';
export class EmailValidator {
static isValid(control: FormControl){
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(control.value);
if (re){
return null;
}
return {"invalidEmail": true};
}
}
@PetraBester
Copy link

Thank you, it works great with my ionic 2 app

@rtpHarry
Copy link

You might want to use this validator on an optional field which at the moment it doesn't support. I changed the snippet to this to let Validators.required handle that:

import { FormControl } from '@angular/forms';

export class EmailValidator {

    static isValid(control: FormControl): any {
        let re =  /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

        // skip validation if empty (Validators.required should handle this)
        if(!control.value) {
            return null;
        }
        
        if(!re.test(control.value)) {
            return {
                "invalidEmail": true
            };
        }

        return null;
    }
}

@zxcfer
Copy link

zxcfer commented Aug 24, 2017

how you use in a form?

@pooja2695
Copy link

pooja2695 commented Sep 1, 2017

how to check with ngIf in html file?
and i'm using ionic2..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment