0

I'm trying to validate a EditText field that should have the format of DD/MM/YYYY date. I tried the following code but it is not giving me the correct answer:

 val dateFormat = "/d{2}(/)/d{2}(/)/d{4}"
        val pattern: Pattern = Pattern.compile(dateFormat)
        val matcher: Matcher = pattern.matcher(editDate.text.toString())
        if (matcher.find()) {
            Log.i("Date","DATE matched! " + editDate.text.toString())
            super.onBackPressed()

        } else {
            editDate.error = "Date format incorrect!"
            Log.i("Date","DATE NOT matched! " + editDate.text.toString())
        }
Mathew Dony
  • 113
  • 1
  • 8
  • 1
    `/d` is `/d` matching pattern, `\d` matches digits. Replace `val dateFormat = "/d{2}(/)/d{2}(/)/d{2}"` with ``val dateFormat = """\d{2}/\d{2}/\d{2}"""``. And to match the entire string either use `.matchEntire` or `if (matcher.matches())` – Wiktor Stribiżew Sep 18 '20 at 08:50
  • also consider that using /d{2} allows any digits from 00 - 99. So even if the pattern matches in the end, the date might not be correct. Option 1: fix your regex with ranges of allowed number, but how can you take the length of different months in to consideration? Option 2: Parse the string to a date and if its valid, all good. Option 3: For a better user experience you should probably use a date picker dialog instead. – just_user Sep 18 '20 at 09:34

0 Answers0