【发布时间】:2017-11-07 07:34:44
【问题描述】:
我应该在模型中进行自定义验证,它可以正常工作,但验证消息未显示且字段未聚焦 这是代码
public class MyValidatorAttribute : ValidationAttribute//RequiredAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
CrossMove obj = (CrossMove)validationContext.ObjectInstance;
var Ci_id_num = (string)value;
string[] memberNames = new string[] { validationContext.MemberName };
if (String.IsNullOrEmpty(obj.Ci_id_num) && obj.Person_typ_cd == "7574")
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName) , memberNames);
}
if(!String.IsNullOrEmpty(obj.Ci_id_num))
{
if(obj.Ci_id_num.Length < 9)
{
ErrorMessage = "رقم الهويه يتكون من 9 خانات";
ErrorMessageResourceName = validationContext.MemberName;
return new ValidationResult("رقم الهويه يتكون من 9 خانات", memberNames);
}
}
return null;
}
}
public class CrossMove
{
[MyValidator(ErrorMessage = "Length should be more than 9 diget")]
public string Ci_id_num { get; set; }
[Required(ErrorMessage = " ")]
public string Person_typ_cd { get; set; }
}
我在动作上使用 json
return Json(new { status = response.StatusCode, transMsg = trans.ToList(), msg = response.Message, toastr = true, alert = true, close = 1 });
如果长度小于 9,则 ModelState 变为 false,但猫科动物不显示消息并且不像其他正常要求那样专注
<div class="form-group form-md-line-input has-error">
@Html.TextBoxFor(x => x.Ci_id_num, new { @class = "form-control", ng_model = "Ci_id_num", placeholder = "رقم الهويه", type = "number" })
<label for="Ci_id_num"> ابحث هنا</label>
@Html.ValidationMessageFor(model => model.Ci_id_num, "", new { @class = "text-danger" })
</div>
【问题讨论】:
-
如果你想通过
@Html.ValidationMessageFor查看验证错误,你应该在你的控制器中返回View(model),而不是Json(以防验证失败)。 -
您期待客户端验证吗?为此,您的属性需要实现
IClientValidatable,并且您需要编写脚本以将规则添加到$.validator- 请参阅The Complete Guide To Validation In ASP.NET MVC 3 - Part 2 -
我尝试返回视图但不起作用。
-
我使用 json 但其他字段验证工作类似:
标签: c# asp.net-mvc validation model