我在使jQuery.Validation工作时遇到问题。我写了一个剧本。所有JS文件都包含在下面。对于我未知的原因,验证始终返回该表格有效。
这是我的JS代码:
$(document).ready(function()
{
$("#contactForm").validate({
rules: {
inputName: "required",
inputSurname: "required",
inputEmail: {
required: true,
email: true
},
inputMessage: "required",
},
messages: {
inputName: "Please enter your firstname",
inputSurname: "Please enter your lastname",
inputEmail: "Please enter a valid email address",
inputMessage: "Please accept our policy"
},
submitHandler: function (form) {
alert('valid form');
form.submit();// for demo
return false; // for demo
}
})
})
在这里你可以找到我的表格:
@using (Html.BeginForm("SendMail", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form", name = "contactForm", id = "contactForm" }))
{
@Html.ValidationSummary(true);
@Html.AntiForgeryToken();
<div class="col-lg-8">
<div id="Contact" class="jumbotron contact-form">
<div class="panel-heading">
<h1 class="panel-title">Kontakt</h1>
</div>
<div class="input-group">
<span class="input-group-addon">Imie</span>
@Html.TextBoxFor(model => model.name, new { @class = "form-control", placeholder = "Twoje imię", id = "inputName" })
</div>
<div class="input-group">
<span class="input-group-addon">Nazwisko</span>
@Html.TextBoxFor(model => model.surname, new { @class = "form-control", placeholder = "Twoje nazwisko", id = "inputSurname" })
</div>
<div class="input-group">
<span class="input-group-addon">Email</span>
@Html.TextBoxFor(model => model.emailAdress, new { @class = "form-control", placeholder = "Adres email", id = "inputEmail" })
</div>
<div class="input-group">
<span class="input-group-addon">Treść<br /> wiadomości</span>
@Html.TextAreaFor(model => model.body, new { @class = "form-control", placeholder = "Treść wiadomości", id = "inputMessage", name = "inputMessage", rows="4" })
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-1">
<button type="submit" class="btn btn-default">
Send Message
</button>
</div>
</div>
</div>
</div>
}
正如您所看到的那样,所有字段都是必需的,但即使我将它们留空,请按提交,jQuery告诉该表单有效。
这里JSFiddle有工作样本:CLICK
答案 0 :(得分:4)
您需要调整rules-object以匹配form-elements的name-attribute。
rules: {
'name': {required:true},
'surname': {required:true},
'emailAdress': {
required: true,
email: true
},
'body': {required: true},
}
在尝试Anto J Subash的版本时,由于大小写,名称属性的命名可能不匹配。 除了Anto J Subash的回答之外,我还强烈建议传递索引字符串化(“'name'”)并避免将其作为“Name”传递,以防止由于JS / jQuery中的保留关键字而导致的问题。
工作JSFiddle
答案 1 :(得分:1)
您必须设置name
而不是id
。您必须根据元素名称设置name
验证的规则。
尝试
$("#contactForm").validate({
rules: {
Name: "required",
Surname: "required",
Email: {
required: true,
email: true
},
Message: "required"
}
})