Friday, July 4

Regex for Validation

What is Regex?

Regex (or regular expression) is sequence of special characters that  match or find string by using pattern.
(Pattern is sequence characters in regex). Which can be use to search, validate or edit text and data.



Regex for Validation

Validate username with regular expression

Condition : Match characters and symbols in the list, a-z, 0-9, underscore, hyphen Length at least 3 characters and maximum length of 15

Regex : ^[a-z0-9_-]{3,15}$

Code Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Give true is all condition matches, otherwise false.
* @param String
* @return boolean
*/
private boolean validateUserName(String username){
Pattern pattern = Pattern.compile("^[a-z0-9_-]{3,15}$");
Matcher matcher = pattern.matcher(username);
return matcher.matches();
}

Validate email with regular expression

Condition : Simple it should be an email address

Regex :  ^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

Code Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Give true is all condition matches, otherwise false.
* @param String
* @return boolean
*/
private boolean validateEmail(String email){
String rEmail = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(rEmail);
Matcher matcher = pattern.matcher(password);
return matcher.matches();
}
view raw RegexEmail.java hosted with ❤ by GitHub

Validate password with regular expression

Condition :
 must contains one digit from 0-9
 must contains one lowercase characters
 must contains one uppercase characters
 contains one special symbols in the list "@#$%"
 match anything with previous condition checking
 length at least 6 characters and maximum of 20

Regex : ((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})
Code Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Give true is all condition matches, otherwise false.
* @param String
* @return boolean
*/
private boolean validatePassword(String password){
Pattern pattern = Pattern.compile("((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})");
Matcher matcher = pattern.matcher(password);
return matcher.matches();
}

No comments:

Post a Comment

Ads Inside Post