jQuery自定义validation:以6开头的电话号码

我有一个表格,您必须输入您的电话号码和其他字段。

我正在使用jQuery Validatevalidation表单。

要validation电话号码字段,我会:

rules: { phone: { required: true, minlength: 9, number:true },.. 

但我还需要检查手机是否以6开头。

我怎样才能做到这一点?

您可以添加自定义validation器

 jQuery.validator.addMethod("phoneStartingWith6", function(phone_number, element) { phone_number = phone_number.replace(/\s+/g, ""); return this.optional(element) || phone_number.match(/^6\d{8,}$/); }, "Phone number should start with 6"); 

并像这样使用它:

 rules: { phone: { required: true, minlength: 9, phoneEnding6: true },.. 

您需要编辑phone_number.match的正则表达式以满足您的要求。

我想你需要添加一个自定义validation器。

 $.validator.addMethod("phoneNumber", function(uid, element) { return (this.optional(element) || uid.match(phone number regex)); } 

您还可以尝试简单的Javascriptfunction

 "Hello World!".startsWith("He"); //true 

注意:此注释/代码适用于未使用jquery validate的用户。