I have tried a lot for this validation but I'm not getting where to put the following code
String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";.
Please help me in this.
I hope this will help. When you Click on Submit button on SWING UI, in actionListener write the validation code.
Emailvalidator emailValidator = new Emailvalidator();
if(!emailValidator.validate(emailField.getText().trim())) {
System.out.print("Invalid Email ID");
/*
Action that you want to take. For ex. make email id field red
or give message box saying invalid email id.
*/
}
This is the seperate class EmailValidator
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Validate hex with regular expression
*
* @param hex
* hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
On a side note, this will enable you that the entered email id is in the correct format. If you want to validate the id, send an email containing a confirmation no and ask the user to enter that number on your UI and then proceed.
The format of an e-mail address can get pretty complex. In fact, its complexity is almost legendary.
The InternetAddress
class in JavaMail is a much more reliable way to parse an e-mail address than a regular expression.
来源:https://stackoverflow.com/questions/15269507/how-to-validate-a-jtextfield-of-email-id-with-a-regex-in-swing-code