How To Validate Date In Dd/mm/yyyy Format In Editext In Android?
I have two edittexts. I want to validate date entered in first edittext when I switch to next edittext... Is it possible? I want to validate in dd/mm/yyyy format strictly.. please
Solution 1:
Step 1
youredittextname.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stubIs_Valid_date(name); // pass your EditText Obj here.
}
});
Step 2
Write a function.
publicvoidIs_Valid_date(EditText edt) throws NumberFormatException {
if (edt.getText().toString().length() <= 0) {
edt.setError("Accept number Only.");
valid_name = null;
} elseif (check your date format using simpledate format) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
} else {
valid_name = edt.getText().toString();
}
}
If you need to know Validate of the date. Please visit this link.
http://www.mkyong.com/regular-expressions/how-to-validate-date-with-regular-expression/
Thank you.
Solution 2:
Use interface TextWatcher
in Android. You have to override its methods:
- In
onTextChanged()
limit the length of text - In
afterTextChanged()
use some good regular expression for date validation. It will be available from Google.
Solution 3:
privatestatic final String DATE_PATTERN="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
private Pattern pattern= Pattern.compile(DATE_PATTERN);
public boolean isValidDate(final String date) {
Matcher matcher = pattern.matcher(date);
if (matcher.matches()) {
matcher.reset();
if (matcher.find()) {
String day = matcher.group(1);
String month = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));
if (date.equals("31") && (month.equals("4")
|| month.equals("6")
|| month.equals("9")
|| month.equals("11")
|| month.equals("04")
|| month.equals("06")
|| month.equals("09"))) {
returnfalse;
} elseif (month.equals("2") || month.equals("02")) {
if (year % 4 == 0) {
if (day.equals("30") || day.equals("31")) {
returnfalse;
} else {
returntrue;
}
} else {
if (day.equals("29") || day.equals("30") || day.equals("31")) {
returnfalse;
} else {
returntrue;
}
}
} else {
returntrue;
}
} else {
returnfalse;
}
} else {
returnfalse;
}
}
Solution 4:
SimpleDateFormat can be of your help. You can look for tutorials or else visit here
Post a Comment for "How To Validate Date In Dd/mm/yyyy Format In Editext In Android?"