Home Tutorial Java Core Java Validations using Regular Expressions

 
 

Java Validations using Regular Expressions
Posted on: August 2, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to validate different fields using regular expressions.

Java Validations using Regular Expressions

In this section, you will learn how to validate different fields using regular expressions. Here we have created the methods to validate the name,address, email and phone number entered by the user. Name should starts with uppercase i.e first character should be capital, Phone number should have the format: XXX-XXX-XXXXXX.

Here is the code:

import java.util.*;
import java.util.regex.*;

class RegularExpressions {

	public static boolean validateName(String name) {
		return name.matches("\\p{Upper}(\\p{Lower}+\\s?)");
	}

	public static boolean validateAddress(String address) {
		return address.matches("\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");

	}

	public static boolean validatePhone(String phone) {
		return phone.matches("^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{6})$");
	}

	public static boolean isEmailValid(String email) {
		boolean isValid = false;
		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;
		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter Name: ");
		String name = input.nextLine();
		while (validateName(name) != true) {
			System.out.print("Invalid Name!");
			System.out.println();
			System.out.print("Enter Name: ");
			name = input.nextLine();
		}

		System.out.print("Enter Phone Number: ");
		String phone = input.nextLine();
		while (validatePhone(phone) != true) {
			System.out.print("Invalid PhoneNumber!");
			System.out.println();
			System.out.print("Enter Phone Number: ");
			phone = input.nextLine();
		}

		System.out.print("Enter Address: ");
		String address = input.nextLine();
		while (validateAddress(address) != true) {
			System.out.print("Invalid Address!");
			System.out.println();
			System.out.print("Enter Address: ");
			address = input.nextLine();
		}

		System.out.print("Enter EmailId: ");
		String email = input.nextLine();
		while (isEmailValid(email) != true) {
			System.out.print("Invalid Email!");
			System.out.println();
			System.out.print("Enter EmailID: ");
			email = input.nextLine();
		}

	}
}
Advertisement

Related Tags for Java Validations using Regular Expressions:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 2, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com