[Android] Create validation for date input!

Date input validation


When the user inputs the date of birth or the reservation date, he / she may want to invalidate the invalid input value or display an error dialog. I summarized the implementation of validation used in such a case!

・ ↓ Click here for "Year" validation implementation ↓ [Android] How to implement validation that repels invalid "years"? ??

Implementation code

ValidationUtil.java


    /**
     *Check if it is a valid date
     *Invalidate dates such as 13th and 32nd
     *
     * @param inputBirthDateString
     * @return
     */
    public static Boolean dateValidation(String inputDateString){

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

        //Point 1
        dateFormat.setLenient(false); 
        Date parsedDate = null;
        try {

        //Point 2
            parsedDate = dateFormat.parse(inputDateString);
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }

        //Point 3
        return dateFormat.format(parsedDate).equals(inputDateString);
    }


Point 1

Lenient: Generous, benevolent, compassionate, (...) generous, tolerant, sweet → setLenient (false) eliminates generosity = means doing a strict check.

The default is true, and with this setting, non-existent dates are automatically moved up or down. (Example: January 32 → February 1)

Point 2

Convert String type to Data type using SimpleDateFormat. If the date is normal, the parse is successful. Returns false if the date is invalid.

Point 3

There seems to be no problem with the processing up to point 2, but there is one problem as it is. That's because SimpleDateFormat processes with a prefix match. → Example: If you create an instance of SimpleDateFormat in the date format of "yyyy / MM / dd", you can format the value "2017/12 / 1A" and it will be treated as "December 1, 2017".

→ So, at the end, "character string to be validated" and "character string after conversion with SimpleDateFormat" are compared, for example, if 2017/12 / 1A is input, false is returned.

Recommended Posts

[Android] Create validation for date input!
Create your own Android app for Java learning
default value for android: exported
Create advanced functions for Yellowfin
Build Spring for Android 2.0.0 environment
Create a name input function