Вопрос

I am using a simple date regex to validate an input string is in the desired format:

In this case dd/mm/yyyy

THE ISSUE

Regular expression for date validation fails in Google Chrome when using type="date":

Displays: dd/mm/yyyy

Renders: yyyy-mm-dd (Here lies the issue)

Chrome date issue


QUESTION

How to use regex (or alternative) to validate a date string across browsers when using type="date"?

NOTE: Using regex to validate yyyy-mm-dd is not a valid solution unless the end user still sees dd/mm/yyyy.

Это было полезно?

Решение

<input type="date" /> internally handles dates like so:

xkcd
> xkcd

Therefore your format should be ^\d{4}-\d\d-\d\d$. Note however that you will need to provide clear instruction to users if their browser doesn't support type="date", or provide a JavaScript calendar alternative, otherwise people won't understand!

Due to the current support for type="date" being so small, it's probably best to use JavaScript and have a hidden input field to store the YYYY-mm-dd format date and validate that, while letting the user type freely into the real input field and try to parse that.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top