简体   繁体   中英

Regular expression in MVC using JavaScript

here is the format of my regular expression:

@"^PR[a-zA-Z0-9-]{36}[0-9]{2}([a-zA-Z0-9-]{3}2[a-zA-Z0-9-]{12}){2,10}$" .

There should be separate validation for each condition. So I succeeded for first three conditions using JavaScript sub-string. Just stuck for last condition ie

"([a-zA-Z0-9-]{3}2[a-zA-Z0-9-]{12}){2,10}" .

In this, I want to check every fourth character must be "2".

How do i achieve this by JavaScript?

If you have the full regex, why not just use it as a whole:

var regex = /^PR[a-zA-Z0-9-]{36}[0-9]{2}([a-zA-Z0-9-]{3}2[a-zA-Z0-9-]{12}){2,10}$/;
var str = "PR12345678901234567890123456789012345600AAA2BBBCCCDDDEEEaaa2bbbcccdddeee";
console.log(regex.test(str)); // true

But if you must really break it, you could do:

var regex1 = /^PR[a-zA-Z0-9-]{36}$/;
console.log(regex1.test(str.substring(0,38))); // true

var regex2 = /^[0-9]{2}$/;
console.log(regex2.test(str.substring(38,40))); // true

var regex3 = /^([a-zA-Z0-9-]{3}2[a-zA-Z0-9-]{12}){2,10}$/;
console.log(regex3.test(str.substring(40,str.length))); // true

See demo fiddle here .

Edit:

To check whether every fourth character must be two, use:

var regexfourth = /^([a-zA-Z0-9-]{3}2)+$/;
console.log(regexfourth.test("aaa2bbb2ccc2ddd2")); // true
console.log(regexfourth.test("aaa2bbb2ccc3ddd2")); // false(notice a 3 after ccc)

Demo fiddle for this here (check the bottom).

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