-5

I have an input field where users are supposed to enter their date of birth. The pattern which I want to use is for example 24-06-2019. So, now I want to make some kind of validation, and if the user entered the wrong pattern there should be some kind of alert. How can I achieve that?

Here is what I got so far:

$('input[name="dateOfBirth"]').on("keyup", () => {
    let current_value = $('input[name="dateOfBirth"]').val();

    // some validation here?
});
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
ST80
  • 3,565
  • 16
  • 64
  • 124
  • 1
    What have you tried so far? – Andreas Jun 25 '19 at 08:15
  • 4
    Before implementing validation on the `keyup` event, consider that the check will fail multiple times before a valid date can be entered. It would be better to perform this check when the form is submitted or on a button click. You would also probably be better off using a [date input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date) instead of validating an input. – frobinsonj Jun 25 '19 at 08:24

1 Answers1

1

Really simple regex:

if (/\d{2}-\d{2}-\d{4}/.test(current_value)) {
    //Date is of correct format
}

If you want to validate the date itself, then just create a new date and check if it's invalid:

const validDate = new Date();
const invalidDate = new Date("abc");
console.log(validDate == "Invalid Date");
console.log(invalidDate == "Invalid Date");
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Using the built–in parser as in `new Date(string)` is a terrible way to validate a date. The first step is to correctly parse the input string (a simple function can suffice or library if desired), then validate the resulting Date object when compared to the input values. – RobG Jun 25 '19 at 09:52