Validate Date entered by Edittext

Asked

Viewed 2,637 times

0

I have an Edittext with Mask to input a date.
How can I validate whether or not the date exists?

Code of my Edittext

NascimentoUsu = (EditText)findViewById(R.id.edtdata_usu);
NascimentoUsu.addTextChangedListener(Mask.insert("##/##/####", NascimentoUsu));
  • You want to validate during typing or at the end?

  • I did not think that any of the solutions would be welcome. I would prefer in the end when I order to save.

1 answer

1


The easiest way to validate would be by using a SimpleDateFormat and using the flag of lenient class DateFormat. The standard is true, to capture formatting errors should use it as false.

Exemplifying:

// Configure o SimpleDateFormat no onCreate ou onCreateView
String pattern = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);

sdf.setLenient(false);

// Durante a confirmacao de cadastro, faça a validacao

String data = NascimentoUsu.getText().toString();

try {
    Date date = sdf.parse(data);
    // Data formatada corretamente
} catch (ParseException e) {
    // Erro de parsing!!
    e.printStackTrace();
}

The flag lenient being true, causes the SimpleDateFormat use a heuristic to correct "wrong data".

With lenient true, the date 29/02/2014 would be converted to 01/03/2014. Using lenient as false, it generates a Parsing error.

  • Thanks for the help, now I’m having another difficulty from having validated the date as I can check if the person is over 18 years?

  • 1

    Take a look at the solution to this question: http://stackoverflow.com/questions/7906301/how-can-i-find-the-number-of-years-between-two-dates-in-android, using the Calendar can make this account.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.