在ViewModel中,我有几个字段的数据注释。
public class EmployeeContactInfoVM
{
[Key]
public int slNo { get; set; }
[Required]
[Display(Name = "Employee GlobalView ID *")]
[StringLength(8,MinimumLength = 8,ErrorMessage ="GV ID should be 8 digits")]
[RegularExpression(@"^[0-9]+$", ErrorMessage = "Please use Numeric data")]
public string EmployeeID { get; set; }
[Required]
[Display(Name = "First Name *")]
[RegularExpression(@"^[a-zA-Z]+[ ]*[a-zA-Z]*$", ErrorMessage = "Please use letters")]
public string FirstName { get; set; }
}
下方给出了我的视图代码
@model EmployeeContactInformation.ViewModel.EmployeeContactInfoVM
@using EmployeeContactInformation.Classes;
@{
ViewBag.Title = "Index";
}
@section Scripts
{
<script src="https://www.google.com/recaptcha/api.js?render=@ViewBag.SiteKey"></script>
<script>
function CreateToken() {
$.blockUI();
grecaptcha.execute('@ViewBag.SiteKey', { action: 'homepage' }).then(function (token) {
document.getElementById("tokenID").value = token;
document.EmpContactFrm.submit();
});
}
</script>
}
@using (Html.BeginForm("Index", "EmployeeContactInformation", FormMethod.Post, new { name ="EmpContactFrm", id = "EmpContactFrmID" }))
{
<div class="form-horizontal" role="form">
<hr />
@Html.ValidationSummary(true)
<input type="hidden" id="tokenID" name="token" />
<div class="form-group" style="margin-bottom:5px">
@Html.LabelFor(model => model.EmployeeID, new { @class = "col-md-2 editor-label" })
<div class="col-md-10 inputText">
@Html.TextBoxFor(model => model.EmployeeID, htmlAttributes: new { @title = "Employee
GlobalView ID should consist of 8 digits and in some countries it may start with a leading
zero" })
@Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FirstName, new { @class = "editor-label col-md-2" })
<div class="inputText col-md-10">
@Html.TextBoxFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SurName, new { @class = "editor-label col-md-2" })
<div class="col-md-10 inputText">
@Html.TextBoxFor(model => model.SurName)
@Html.ValidationMessageFor(model => model.SurName)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="button" value="Submit" class="btn btn-create btnSave" style="font-size:
large;font-weight: 600;padding: 10px;" />
</div>
</div>
}
表单在CreateToken函数(document.EmpContactFrm.submit((;(中提交。
我假设所有的验证都发生在客户端,因为我已经包括了在配置文件中。
一些验证发生在客户端,例如,如果我输入7位数的EmployeeID,我会收到一条消息,说"GV ID应该是8位数"。
当我在没有输入必填字段的情况下提交表单时,客户端验证不起作用,控件将转到Action Method。
我在代码中包含了服务器端验证,比如if(ModelState.IsValid(,当我错过强制字段时,这将引发验证错误。
我需要在服务器和;客户端?我假设,如果我们包括jquery不引人注目的文件&上面提到的配置设置、验证可以完全在客户端进行。
请让我知道
从更改此行
@Html.ValidationSummary(true)
至
@Html.ValidationSummary()
阅读此答案