当前,当用户单击“创建帐户”按钮时,使用DataAnnotations可以进行预期的字段验证
我有一个名为 form-data 的表单,其中包含3个字段(产品名,描述,注释)。
当用户单击创建时,验证将按预期显示在表单上。我想要实现的是循环表单并捕获失败的字段并存储在fields对象中。因此,我希望看看product_name或description是否正确。即字段=产品名称,说明
所以我在下面有这个代码。由于某种原因,该元素仅在第一个名为product_name
的字段中返回一个[Required("Product name is required")]
[StringLength(9, ErrorMessage="Must be under 9 characters")]
public string product_name {get; set;}
[Required("Descriptioon is required")]
[StringLength(20, ErrorMessage="Must be under 20 characters")]
public string Description {get; set;}
[Required("Comment is required")]
[StringLength(20, ErrorMessage="Must be under 50 characters")]
public string Comment {get; set;}
@using (Html.BeginForm("Register", "Product", FormMethod.Post, new { @id = "form-data" }))
@Html.ValidationSummary(true, "", new { @class = "styled" })
<div class="form-group">
@Html.LabelFor(model => model.product_name)
@Html.TextBoxFor(model => model.product_name, new { @class = "form-control", @placeholder = "Please enter here" })
@Html.ValidationMessageFor(model => model.product_name, "", new { @class = "styled" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description)
@Html.TextBoxFor(model => model.Description, new { @class = "form-control", @placeholder = "Please enter here" })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "styled" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.Comment)
@Html.TextBoxFor(model => model.Comment, new { @class = "form-control", @placeholder = "Please enter here" })
@Html.ValidationMessageFor(model => model.Comment, "", new { @class = "styled" })
</div>
<button id="btnCreateAccount" type="submit" onclick="onCreateAccount()">Create Account</button>
}
@section Scripts {
<script type="text/javascript">
function onCreateAccount()
{
var elements = $("#form-data").data("validator").errorList;
var fields =[]
for (var i = 0; i < elements.length; i++) {
fields = elements[i];
}
}
</script>
}
有什么主意我可以将其存档吗?