Validate Date entry by EditText

0

I have an EditText with Mask for entering a date. How can I validate whether the date exists or not?

Code of my EditText

NascimentoUsu = (EditText)findViewById(R.id.edtdata_usu);
NascimentoUsu.addTextChangedListener(Mask.insert("##/##/####", NascimentoUsu));
    
asked by anonymous 03.09.2014 / 15:19

1 answer

1

The easiest way to validate would be to use a SimpleDateFormat and using the flag of lenient "of class DateFormat . The default 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 lenient flag being true , causes SimpleDateFormat to use a heuristic to correct "wrong" data.

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

    
03.09.2014 / 15:49