Java Validations using Regular Expressions


 

Java Validations using Regular Expressions

In this section, you will learn how to validate different fields using regular expressions.

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\\.-][email protected]([\\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();
		}

	}
}

Ads