Wednesday, July 20, 2005

EMail Validation using Regular Expressions

Using Regular Expressions in Java, we can validate where the given email-id string is of the valid format. Here is a sample.

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

public static boolean validateEmailId(String astrEmailId) {
//Set the email pattern string
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
//Match the given string with the pattern
Matcher m = p.matcher(astrEmailId);
//check whether match is found
return m.matches();
}

RegExp can also be used in JavaScriptto validate EMail ID

function isEmail(str) {
// are regular expressions supported?
var supported = 0;
if (window.RegExp) {
var tempStr = "a";
var tempReg = new RegExp(tempStr);
if (tempReg.test(tempStr)) {
supported = 1;
}
}
if (!supported) {
return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}
var r1 = new RegExp("(@.*@)(\\.\\.)(@\\.)(^\\.)");
var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.
([a-zA-Z]{2,3}[0-9]{1,3})(\\]?)$");
return (!r1.test(str) && r2.test(str));
}

No comments:

Total Pageviews

Reading List - 05-Mar-23

Talking to #AI may be the most important job skill of this century ( JohnGoodPasture ) Role of account management over the years. It’s a ro...