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\\-\\.]+\\.
return (!r1.test(str) && r2.test(str));

No comments:


Popular Posts (Last 30 days)

This is a personal blog and I do not speak for my employer.