Validation in Java/Android

Many time during my Android development, I need to verify email address, username, password or any specific requirements. Most of times it needs when I am building registration form or login form. So I made the function that takes first argument as string on which validation is needed and pattern [Regular Expression] that decides first argument is valid or invalid.

Here I use two main java class

Here Pattern class compile the regular expression and then Matcher class perform match operation against given String using compiled pattern. Here is the function for that.

	public Boolean validate(String text, String regex)	{
		Pattern pattern;	
		Matcher matcher;
		pattern = Pattern.compile(regex);
    	matcher = pattern.matcher(text);
    	if(matcher.matches())	{
    		return true;
    	else	{
    		return false;

Here you can see that the function validate validates the String text against the regex using Pattern and Matcher class. I attached the example of email validation below, but you can use any validation by just providing their regular expression.

Download example of email validation with comments here :

References :

IP address validation in javascript

In javascript, we have to do validation at client side. For that purpose we have regex [Regular Expression]. But for some complex or specific requirement we have to build some logic at our own. So here the function check whether the IP address enter in textbox is correct or not and return true or false accordingly.

Functino for IP validation in javascript.

Code :

function checkIpAdd(id)
	var ipAdd = document.getElementById(id).value;
	if(ipAdd.substr(0, 3) > 255 || ipAdd.substr(4, 3) > 255 || ipAdd.substr(8, 3) > 255 || ipAdd.substr(12, 3) > 255)	
                return false;
        else    return true;