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 桁にする必要があります」というメッセージが表示されます。
必須フィールドに入力せずにフォームを送信すると、クライアント側の検証が機能せず、コントロールがアクション メソッドになります。
コードに if(ModelState.IsValid) のようなサーバー側検証を含めました。これにより、必須フィールドを見逃したときに検証エラーがスローされるようになりました。
サーバー エンドとクライアント エンドの両方で検証を含める必要がありますか? jquery 控えめなファイルと上記の構成設定を含めると、検証は純粋にクライアント側で行うことができると想定していました。
私にお知らせください