Home > Mobile >  Angular 13 Typescript RegExp Date format dd/mm/yyyy
Angular 13 Typescript RegExp Date format dd/mm/yyyy

Time:06-02

im working in Angular 13 project i want to create a directive to allow user only type numbers and '/' foor my date input. dd/mm/yyyy. this is my Regx :

   if (!String(myVal).match(new RegExp(/^\d $/))) {
        event.preventDefault();
    }

this condition is working but i can type only numbers can't type / to format my date. any suggestion to moify my Regx.

Regards

CodePudding user response:

You can only type numbers with your Regex because ^\d $ only allows numbers. If you're looking for a RegEx to validate the final date, it would look like this:

"01/06/2022".match(/^\d{2}\/\d{2}\/\d{4}$/)

Explanation:

  • ^ matches the start of the string
  • \d{2} matches exactly two digits
  • \d{4} matches exactly four digits
  • \/ is an escaped forward slash (/), and you need to escape it
  • $ matches the end of the string
  • You don't need to explicitly instantiate new RegExp, because that's done automatically when you define your Regex between the two /.

If you're looking for a Regex to only allow the typing of characters used in the date, it would look like this:

"01/06".match(/^[\d\/] $/)

Read that as "only match if there's at least one (that's what the means here) of the characters that are between [ and ], that is: either digits (\d) or /".

And of course there are other ways to validate a date once it's fully typed, apart from a Regex (the Regex would permit dates like 99/99/9999).

  • Related