2017  Kodetalk | Feedback | Privacy Policy | Terms | About

how to validate email using regex in java or javascript

For example i want to validate a email id is really valid email id or not using regex in java. What would be the best way to do so?

For java we can use below code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternValidator {
    private Pattern pattern;
    private Matcher matcher;

    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,})$";

    public PatternValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);

     * Validate email with regular expression
     * @param email
     *            email for validation
     * @return true valid email, false invalid email
    public boolean validate(final String email) {
        matcher = pattern.matcher(email);
        return matcher.matches();


and for javascript we can use below code:

function validateEmail(mail)  

 if (/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(mail)) 
    return (true) 
    alert("You have entered an invalid email address!") 
    return (false) 

Answer is