我有一个联系表单,我试图添加一个简单的验证码,将两个数字加在一起,并在发送表单时显示successMessage div。我的表格看起来像这样;
<form method="post" action="" id="contact">
<div id="successMessage" style="display:none;">Message sent</div>
<label for=name accesskey=U><span class="required">*</span> Your Name</label>
<input name="name" type="text" id="name" size="30" value="" />
<br />
<label for=email accesskey=E><span class="required">*</span> Email</label>
<input name="email" type="text" id="email" size="30" value="" />
<br />
<label for=phone accesskey=P><span class="required">*</span> Phone Number</label>
<input name="phone" type="text" id="phone" size="30" value="" />
<br />
<label for=comments accesskey=C><span class="required">*</span> Your Comments</label>
<textarea name="comments" cols="26" rows="8" id="comments"></textarea>
<hr />
<p style="margin:0px; padding:0px;"><span class="required">*</span>Are You Human?</p>
<label for=verify accesskey=V>3 + 1 =</label>
<input name="verify" type="text" id="verify" size="6" value="" />
<input name="contactus" type="submit" class="submit" id="contactus" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$.validator.addMethod("verify", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {3} + {1}"));
$("#contact").validate({
success: function(label) {
label.hide();
},
rules: {
name: {required: true},
email: {
email: true,
required: true
},
phone: {
digits: true
},
comments: {required: true}
},
messages: {
name: "Please tell us your Name",
email: "Please enter a valid email address",
comments: "Please enter your comments"
}
});
});
</script>
您可以看到我尝试使用addMethod来验证有人在验证字段中输入4,但它没有验证该字段。
如果有人可以帮助我完成工作并在表单提交时也显示全局成功消息,我将不胜感激。
谢谢。
答案 0 :(得分:0)
您指定了方法,但未使用它。这是Javascript中的简单修复。
<script type="text/javascript">
$(function() {
$.validator.addMethod("verify", function(value, element, params) {
return this.optional(element) || parseInt(value, 10) == params[0] + params[1];
}, jQuery.validator.format("Please enter the correct value for {0} + {1}"));
$("#contact").validate({
success: function(label) {
label.hide();
},
rules: {
name: {required: true},
email: {
email: true,
required: true
},
phone: {
digits: true
},
comments: {required: true},
verify:{
verify:[3, 1]
}
},
messages: {
name: "Please tell us your Name",
email: "Please enter a valid email address",
comments: "Please enter your comments"
}
});
});
</script>
答案 1 :(得分:0)
让每个人都知道你需要解析整数,因为值是一个字符串。你正在做一个平等,所以他们都需要是整数。
用parseInt包装'value',如下所示:
return this.optional(element) || parseInt(value, 10) == params[0] + params[1];