-1

I need to validate date in string to the format of yyyy-MM-dd using regular expressions.

now I can check whether the string matches that format or not by:

if value.matches("^[0-9]{4}-[0-9]{2}-[0-9]{2}") {

but it also accepts 2009-90-90 and that's invalid date.

So how can I add range in my regular e.g no more than 12months in the date.

Thank you

Abdulkadir Ugas
  • 415
  • 5
  • 13
  • Possible duplicate of [Regex date validation for yyyy-mm-dd](https://stackoverflow.com/questions/22061723/regex-date-validation-for-yyyy-mm-dd) – vs97 Aug 17 '19 at 14:00
  • 1
    Possible duplicate of [Regex to validate date format dd/mm/yyyy](https://stackoverflow.com/questions/15491894/regex-to-validate-date-format-dd-mm-yyyy) – Code Maniac Aug 17 '19 at 14:01
  • Using a regex for this is a very bad choice of tools. – rmaddy Aug 17 '19 at 15:26

1 Answers1

1

A regex isn't the most appropriate way of validating a date. Use a date formatter instead:

let formatter = DateFormatter()

formatter.dateFormat = "yyyy-MM-dd"

let str = "2019-02-28"

let dateIsValid = formatter.date(from: str) != nil
ielyamani
  • 17,807
  • 10
  • 55
  • 90
  • But, what if my incoming data isn't standard? My dates are all dd-MMM-yyyy, but my dates times have different delimiters, sometimes a ":" and sometimes an "h". – Zonker.in.Geneva Jan 12 '20 at 18:31