简体   繁体   English

在JQuery Form Validation正则表达式中定义空间

[英]Defining a space in JQuery Form Validation regex expression

I am validating a form using jQuery form validation, one of the field needs to be four digits space four digits, eg 1234 5678 我正在使用jQuery表单验证来验证表单,其中一个字段需要为四位数,四位数,例如1234 5678

I can get it to validate if I replace the space with a hyphen: 我可以通过连字符替换空格来验证它:

$.validator.addMethod("companynumber", function(value, element) {
var regexp = /^[0-9]{4}[-][0-9]{4}$/;
var strippedValue = value.replace(/\s/g, '');
return this.optional(element) || regexp.test(strippedValue);
},  "Enter a valid Company Number.");

But cannot find what I need to put in the regex for a single space between the digit blocks, can anybody help please? 但是找不到我需要在数字块之间的单个空格中放入正则表达式的内容,有人可以帮忙吗?

Acheong87 is right that you can just get a space with /^[0-9]{4} [0-9]{4}$/ , but it looks like you are also stripping out spaces before you check against the regex. Acheong87是正确的,您可以使用/^[0-9]{4} [0-9]{4}$/来获得一个空格,但是看起来您在检查正则表达式之前也要删除空格。 If you want the regex to match properly you shouldn't be using strippedValue to do the regexp.test. 如果希望正则表达式正确匹配,则不应使用strippedValue进行regexp.test。

So something like this should work: 所以这样的事情应该工作:

$.validator.addMethod("companynumber", function(value, element) {
var regexp = /^[0-9]{4} [0-9]{4}$/;
return this.optional(element) || regexp.test(value);
},  "Enter a valid Company Number.");

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

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