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

5
  • 1
    Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the [<>] snippet editor. Commented May 18, 2020 at 13:29
  • Sounds like you could use moment.js or luxon and feed them the format Commented May 18, 2020 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 and validation Commented May 18, 2020 at 13:34
  • Can I do it without moment and any other library Commented May 18, 2020 at 14:26
  • @MalkhaziDartsmelidze—yes, but you'll need to write your own parser and tokeniser (e.g. this answer). Commented May 18, 2020 at 20:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes but admin user can't enter regex to for validation, they must enter only format y, m, d
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.
Take a look at Moment.js. I think using this library this can be achieved ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.