我正在编写扩展方法以将正则表达式验证应用于不同的文本框。多个JQuery验证仅适用于单个文本框
HTML
<form class="getintouch_form" name="Form_ContactUs" action="" id="frm">
<div class="getintouchform_field">
<label class="inputform_label">Your Name*</label>
<input class="inputform_textfld" type="text" placeholder="John Smith" maxlength="50" name="Name" id="TxtName" />
</div>
<div class="getintouchform_field">
<label class="inputform_label">Your Email Address*</label>
<input class="inputform_textfld" type="text" placeholder="[email protected]" name="Email" id="TxtEmailId" />
</div>
<div class="getintouchform_field">
<label class="inputform_label">Best number to call you back on*</label>
<input class="inputform_textfld" type="text" placeholder="Telephone or Cell number" name="ContactNumber" id="TxtContactNumber" />
</div>
<div class="getintouchform_field">
<label class="inputform_label">Company Name*</label>
<input class="inputform_textfld" type="text" placeholder="Company Name" name="CompanyName" id="TxtCompanyName" />
</div>
<div class="getintouchform_field">
<label class="inputform_label">Role in an Organization*</label>
<input class="inputform_textfld" type="text" placeholder="Role in an Organization" name="Role" id="TxtRole" />
</div>
<div class="getintouchform_field">
<label class="inputform_label">Optional Message</label>
<textarea class="inputform_textarea" placeholder="Type your message here..." id="OptionalMessage"></textarea>
</div>
<button class="submitbtn bluebutton" id="BtnSend" type="button">send</button>
</form>
jQuery的
var _form = $("#frm");
$.validator.addMethod(
"Email",
function(value, element) {
return /^([a-zA-Z0-9._-][email protected]@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5})$/i.test(value);
},
"Please enter a valid email address."
);
$.validator.addMethod(
"Name",
function(value, element) {
return /^[a-zA-Z]+([a-zA-Z ]+)*$/i.test(value);
},
"Please enter a valid Name."
);
$.validator.addMethod(
"ContactNumber",
function(value, element) {
return /^[A-Z0-9 _]*[A-Z0-9][A-Z0-9 _]*$/i.test(value);
},
"Please enter a valid ContactNumber."
);
_form.validate({
onfocusout: function(element) {
$(element).valid();
},
rules: {
Name: {
required: true
},
Email: {
required: true
//email: true
},
ContactNumber: {
required: true,
maxlength: 15
},
CompanyName: {
required: true
},
Role: {
required: true
}
},
messages: {
Name: {
required: "Name is mandatory field."
},
ContactNumber: {
required: "Contact Number is mandatory field. ",
maxlength: "Invalid Contact Number.",
phoneUS: "Invalid Contact Number."
},
Email: {
required: "Email is mandatory field."
},
CompanyName: {
required: "Company Name is mandatory field."
},
Role: {
required: "Role In Organization is mandatory field."
}
},
submitHandler: function(form) {
_insertData();
}
});
CodePen:https://codepen.io/anon/pen/ybwvwv
我怀疑是因为所有的输入都有'name =“something”',并且它将该属性与验证方法相匹配。 – Barmar
但正如你所看到的,所有的文本框有不同的名称值 –
你可以检查codepen以及 –