Thursday, July 12, 2018

Grails on Groovy over Java > Email Address Validation Using Regex

Below is a sample code snippet to validate email address using REGEX
package com.pkm;

import java.util.regex.Pattern;

public class EmailValidationRegex {
    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+([\\.\\+]?[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    private static Pattern _pattern = null;

    public static void main(String[] args) {
        check("pritomkucse+regex.test@gmail.com");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm");
        check("pkm@c.commmmmmmmmmmmmmmmmmmmm.");
        check("pkm.+invalid@no.valid");
    }

    static void check(String email) {
        System.out.println(email + " > " + valid(email).toString().toUpperCase());
    }

    static Boolean valid(String email) {
        return getPattern().matcher(email).matches();
    }

    static Pattern getPattern() {
        if (_pattern != null) return _pattern;
        _pattern = Pattern.compile(EMAIL_PATTERN);
        return _pattern;
    }
}

No comments:

Post a Comment