Email Address Verification in Java

#1 Check email format with an efficient regular expression.
#2 Check mail server

	private boolean isValidEmailAddress(String emailAddress){
		boolean isValidWithRegex = isValidWithRegex(emailAddress);
		if(isValidWithRegex){
			String domainIp = "";
			int atPos = emailAddress.indexOf('@');
			String domianName = emailAddress.substring(atPos+1);
			try{
				InetAddress address = InetAddress.getByName(domianName);
				domainIp = address.getHostAddress();
			}
			catch(UnknownHostException unknownHost){
				logger.info("Host not found");

			}
			if(domainIp.length()>0) return true;
			else return false;
		}
		else return false;
	}

	private boolean isValidWithRegex(String emailAddress){
		String regex= "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(emailAddress);
		if(matcher.matches()) return true;
		else return false;
	}

For any web application, there must be a front end form validation mechanism. Incorrect data should not be sent to the back end on the first place.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s