简体   繁体   English

书面模式与字符串 Javascript/jQuery 不匹配

[英]Written pattern not matching with string Javascript/jQuery

I'm validating text field for following data pattern "I-MH-ABCD-ABC-1222";我正在验证以下数据模式的文本字段“I-MH-ABCD-ABC-1222”;

Following is a RegEx I've written and it is not working.以下是我编写的正则表达式,但它不起作用。

var router_added_sap = "I-MH-ABCD-ABC-1222";
var pattern = /^[a-zA-Z]{1}\-[a-zA-Z]{2}\-[a-zA-Z]{4}\-[a-zA-Z]{3}\-\d/;

if(!router_added_sap.match(pattern))
{
   alert("Please Enter Right SAP-IDasa");
   return false;
}

Though user write correct pattern script is giving me an alert message.尽管用户编写正确的模式脚本给了我一条警报消息。

Definitely no need to escape the dashes.绝对没有必要逃避破折号。 You also need to group each of these together.您还需要将这些组合在一起。 If these are being used in a single field by itself then I would recommend making sure to check for the start of the string (^) and the end of the string ($) and apply the ignore case flag at the end (i).如果这些单独用于单个字段,那么我建议确保检查字符串的开头 (^) 和字符串的结尾 ($),并在结尾 (i) 应用忽略大小写标志。 The (+) just at the end is a quantifier that will check for 1 or more digits and grab all of them.最后的 (+) 是一个量词,它将检查 1 个或多个数字并获取所有数字。 So I would rewrite it as such.所以我会这样重写它。

var router_added_sap = "K-MH-ABCD-ABC-1222";
var pattern = /^([A-Z]{1})-([A-Z]{2})-([A-Z]{4})-([A-Z]{3})-\d+$/i;

if(!router_added_sap.match(pattern))
{
   alert("Please Enter Right SAP-IDasa");
   return false;

}

http://www.regexr.com/ is great for helping build Regular Expressions. http://www.regexr.com/非常适合帮助构建正则表达式。 I also keep a great cheat sheet printed off on my desk that I found here: http://cheatography.com/1/cs/5/我还在我的桌子上打印了一张很棒的备忘单,我在这里找到了: http : //cheatography.com/1/cs/5/

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

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