简体   繁体   English

不能对正则表达式设置限制

[英]can not set limit on regex

I have this function called vatValidate , which is used to validate VAT format of user inputs.我有一个名为vatValidate函数,用于验证用户输入的增值税格式。 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 .如果用户输入与预定义序列匹配,则该函数记录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}$/当我研究这样做时,例如对于奥地利,我必须使用^$定义正则表达式,结果为: /^[U]{1}[0-9]{8}$/

Apparently this should work just fine, as I verified it in regex101.com and can be seen below:显然这应该可以正常工作,因为我在 regex101.com 中验证了它,可以在下面看到:

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

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.我的开发环境是 Laravel,这段代码在刀片内的脚本标签中执行。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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