0

i have this format for dates yyyy-MM-dd

and generating the following reged

 /^[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]$

This is generated in java using the following where i replace the format with regex

String format = getDisplayDateFormat( formatType );

        format = format.replaceAll("\\-","\\\\-");
        format = format.replaceAll("y","[0-9]");
        format = format.replaceAll("M","[0-9]");
        format = format.replaceAll("d","[0-9]");

        return "^" + format + "$";

If i run this through a regex validator its fine, but chrome is giving the following error

Pattern attribute value ^[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]$/: Invalid escape

edit to include html

<input type="text" value="2020-04-21" placeholder="yyyy-mm-dd" pattern="^[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]$" data-minimum-value="2020-08-10" data-maximum-value="2020-08-13"id="F112407" maxlength="10" data-date-format="YYYY-MM-DD" >

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Adam
  • 1,136
  • 8
  • 26
  • 51
  • That regex *is* valid. Chrome is giving that error when you do what, exactly? – Federico klez Culloca Apr 27 '20 at 13:33
  • 1
    You shouldn't escape the ASCII dash (`-`) – Erwin Bolwidt Apr 27 '20 at 13:33
  • @FedericoklezCulloca when its added to the input pattern – Adam Apr 27 '20 at 13:37
  • How are you running this in Chrome? – VLAZ Apr 27 '20 at 13:38
  • `-` is special character *only inside character class* `[...]` where it can be used to create range of characters. Outside of character class it isn't special and represents only character `-` so it doesn't need to be escaped (although escaping it there is allowed in many regex engines/flavors so it shouldn't cause any errors). How exactly are you using this regex? Please provide [mcve] which will allow us to reproduce your problem. – Pshemo Apr 27 '20 at 13:38
  • @ErwinBolwidt could you show me what you mean in an answer – Adam Apr 27 '20 at 13:38
  • 1
    @ErwinBolwidt but that shouldn't produce an invalid regular expression. An escaped dash in a regex (outside a character class) will just be a dash again. It's not invalid. – VLAZ Apr 27 '20 at 13:39
  • 3
    You can't validate a date using regular expressions. Is 9999-99-99 a valid date? – ataravati Apr 27 '20 at 13:39

1 Answers1

1

See also: Pattern attribute value is not a valid regular expression

The valid pattern would be: ^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$

EDIT: However, there are more fool proof ways to validate dates. Consider using a date validation function, for example: How to validate date with format "mm/dd/yyyy" in JavaScript? Or use a date-picker to limit the input altogether.

estherwn
  • 156
  • 6