Regular expression validating date

Rated 4.5/5 based on 505 customer reviews

Through a list of examples , we will build a script to validate phone numbers , UK postal codes, along with more examples.

First, let’s start by building the webpage and the validation code then we will talk about the regular expressions used to validate the strings.

Then I created a variable that contains the result of running the test() function on the phone Number string which will be a boolean that contain either true if the string matches our regular expression or false if it does not.

Then I created my regular expression and attached it to a variable called phone RGEX notice that I did not need to wrap the regular expression in quotes this is because javascript natively recognizes regular expressions so there is no need to create them as strings then convert them.

The other issue is that regular expressions don’t deal directly with numbers. That’s because the characters for the digits 0 through 9 occupy consecutive positions in the ASCII and Unicode character tables.

You can’t tell a regular expression to “match a number between 1 and 31”, for instance. See Chapter 6 for more details on matching all kinds of numbers with regular expressions.

Because of this, you have to choose how simple or how accurate you want your regular expression to be.

If you already know your subject text doesn’t contain any invalid dates, you could use a trivial regex such as cannot repeat more than two times or fewer than two times.

Leave a Reply