简体   繁体   中英

javascript function to make sure string is in the format m/d/yyyy

I am trying to validate a string against a regular expression and I have the JS code as below :

var regx = new RegExp("([1-9]|1[012])[- /.]([1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d");

if (!regx.test(document.getElementById('toDate').value)) {
     alert('invalid from date format... ');
     return false;
}

I tried to test it with the value 7/4/2017 and it fails...

Do I have my regex wrong?...

You can write a regular expression that validates both the character format and the validity of the values as dates, but that's the hard way.

I recommend tackling the problem in two steps: format validation, followed by value validation.

Step 1. Validate m/d/yyyy format

The format is simple. 1 or 2 digits, a slash, 1 or 2 digits, another slash, and 4 digits.

/\d{1,2}\/\d{1,2}\/\d{4}/.test('1/4/2018')
//> true

Step 2: validate the string as a legitimate date

I think the simplest way to check if a string represents a valid date is to attempt to construct a Date based on it, and then check to see if the construction produces the results you expect.

var potentialDate = new Date(year, month, day)

Again, you can use a regex to extract the year, month, and day portions of the string.

var parts = string.match(/(\d{1,2})\/(\d{1,2})\/(\d{4})/);
var potentialDate = new Date( parts[3] , parts[1] , parts[2] );

Or, if you value raw simplicity, you can just split on '/' , since you've already confirmed the basic format.

Finally, interrogate the date object to ensure that none of the constituent parts overflowed.

if( potentialDate.getFullYear() !== parseInt( parts[3] ) ) { /* error */ }
// etc.

This last step is needed because javascript permits this:

new Date(2018, 13, 1)
//> Tue Feb 05 2019 // month "13" has overflowed to push date into 2019

--

This is hard mode. Use something like momentjs or date-fns.

Because you are using the RegeExp constructor you will need to use double slashes escape the numeric matches so \\\\d instead of \\d .

If you want to instead use RegExp literal syntax you could but you would need to escape the forward slashes. Also it's generally a good idea to escape dashes inside square brackets.

This should work: /([1-9]|1[012])[\\- \\/.]([1-9]|[12][0-9]|3[01])[\\- \\/.](19|20)\\d\\d/

https://regex101.com/ is really helpful for this sort of thing.

Here is a link to your regex already input into regex101.com https://regex101.com/r/Q1uyan/1

notice that when you don't escape the forward slashes it gives an error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM