简体   繁体   中英

can not set limit on regex

I have this function called vatValidate , which is used to validate VAT format of user inputs. Currently it performs validation for two countries, Austria and Italy as default case. For each, I specified the expected user input sequence for related VAT format with regular expression.

 function vatValidate() { let vatFormat; let countryCode = document.getElementById('countries').value; switch (countryCode) { case 'Austria': countryCode = 'AT'; vatFormat = /[U]{1}[0-9]{8}/; break; default: countryCode = 'IT'; vatFormat = /[0-9]{11}/; } let vatNumber = document.getElementById('pivaid').value; let vat = countryCode + vatNumber; if (vatFormat.test(vat)) { console.log('Correct'); } else { console.log('Error'); } } vatValidate()

If user input matches the predefined sequence, the function logs true else false . It works fine, but the problem is, that the regex code I defined, does not enforce the length of the sequence. As I have studied to do so, for instance for Austria, I have to define the regex using ^ and $ resulting in: /^[U]{1}[0-9]{8}$/

Apparently this should work just fine, as I verified it in regex101.com and can be seen below:

奥地利案例的正则表达式代码验证

Now the problem is, that as soon as I add ^ and $ in my code, it won't work any longer and it just logs an error! My development environment is Laravel and this code is executed in a script tag inside a blade.

使用这个正则表达式表达式解决了奥地利的问题:

/^[A]{1}[T]{1}[U]{1}[0-9]{8}$/

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