1

Hello I have problem validating and confirming date format of given date.

Admin enters valid date format for input and user enters date in input.

For example: User enters 2020-05-10 and admin has entered Y-m-d my validation function must return true

Both inputs are dynamic and I don't have idea how to confirm format

I saw this solution but this is not dynamic: Check date format in JavaScript

Any help will be apreciated

Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
  • 1
    Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan May 18 '20 at 13:29
  • Sounds like you could use moment.js or luxon and feed them the format – mplungjan May 18 '20 at 13:29
  • `2020-05-10`'s format is not `Y-m-d`. By convention, the format is `YYYY-MM-DD` (Year with 4 digits, month with two digits, day with two digits). Look at Moment's [format](https://momentjs.com/docs/#/displaying/format/) and [validation](https://momentjs.com/docs/#/parsing/is-valid/) – Jeremy Thille May 18 '20 at 13:34
  • Can I do it without moment and any other library – Malkhazi Dartsmelidze May 18 '20 at 14:26
  • @MalkhaziDartsmelidze—yes, but you'll need to write your own parser and tokeniser (e.g. [this answer](https://stackoverflow.com/a/57302039/257182)). – RobG May 18 '20 at 20:13

1 Answers1

0

You can achieve it using a regular expression.

Suppose if admin enters date format Y-m-d than you can validate user input like :

function validate() {
  var date = document.getElementById("date").value;
  if (date.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/)) {
    alert("Valid");
  } else {
    alert("Invalid");
  }
}
<input type="date" id="date" onchange="validate()" />

Change regular expression for other date formats.

TRK
  • 188
  • 1
  • 7
  • Yes but admin user can't enter regex to for validation, they must enter only format y, m, d – Malkhazi Dartsmelidze May 18 '20 at 14:45
  • You can get format entered by admin in your javascript code then you can put if-else/switch-case condition according to date format with regex to validate date. – TRK May 18 '20 at 14:52
  • Take a look at [Moment.js](https://momentjs.com/docs/#/displaying/format/). I think using this library this can be achieved .. – Monster Brain May 18 '20 at 15:13