我在ASP.Net中有一个观点。我在视图中添加了一些控件。我在将数据发送到服务器之前尝试进行客户端验证。如果一切正常,我想将其发送到服务器 我的代码在这里:
@using (Html.BeginForm("Index", "staff", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="form-group has-feedback">
<div> @Html.LabelFor(a => a.staff_name, "Staff Name")</div>
@Html.TextBoxFor(a => a.staff_name, new { @class = "form-control", placeholder = "", required = "required", autofocus = "autofocus"})
</div>
<div class="form-group has-feedback">
<div> @Html.LabelFor(a => a.user_name, "Username")</div>
@Html.TextBoxFor(a => a.user_name, new { @class = "form-control", placeholder = "", required = "required" })
</div>
<div class="form-group has-feedback">
<div> @Html.LabelFor(a => a.password, "Password")</div>
@Html.PasswordFor(a => a.password, new { @class = "form-control", placeholder = "", required = "required",id="password" })
</div>
<div class="form-group has-feedback">
<div> @Html.LabelFor(a => a.confirm_password, "Confirm Password")</div>
@Html.PasswordFor(a => a.confirm_password, new { @class = "form-control", placeholder = "", required = "required", id = "c_password" })
</div>
<div class="row">
<div class="col-xs-3 ">
<button type="submit" class="btn btn-primary btn-md pull-right" onsubmit="validateForm()">Submit</button>
</div><!-- /.col -->
</div>
}
</div>
</section>
<script type="text/javascript">
function validateForm()
{
var pass = document.getElementById("password").value;
var c_pass = document.getElementById("c_password").value;
if(pass==c_pass)
{
//submit
}
}
</script>
我想检查'密码'和'确认密码'是否匹配。如果是,则只发布在服务器上。
答案 0 :(得分:0)
嘿,您只需要在web.config文件中启用客户端验证,就不需要为此编写任何外部代码。 您可以在web.config文件中添加以下代码行
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
希望它适合你!
答案 1 :(得分:0)
您应该在@{ Html.EnableClientValidation(true); }
之前使用@Html.BeginForm
启用客户端验证并使用jquery validate()
使用它来激活客户端验证。
<script type="text/javascript">
$(document).ready(function() {
$("#yourFormId").validate({
rules: {
ConfirmPassword: {
equalTo: "#Password"
},
},
messages: {
confirm_password: {
equalTo: "Please enter the same password as above"
},
}
});
});
</script>