模型Asp.net mvc中的Custom ValidationResult

时间:2017-11-07 07:34:45

标签: c# asp.net-mvc validation model

我应该在模型中进行自定义验证,它的工作正常但验证消息没有显示,并且字段没有聚焦 这是代码

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变为假

<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>

1 个答案:

答案 0 :(得分:0)

这是解决此问题的简便方法 我发送有错误的字段数组

var erroneousFields = ModelState.Where(ms => ms.Value.Errors.Any())
                                    .Select(x => new { x.Key , x.Value.Errors });

然后我写了几个javascript来显示消息并且焦点第一个字段在数组中有错误

if (json.Keys.length > 0) {
                        $("#" + json.Keys[0].Key + "").focus();
                        console.log(json.Keys[0].Errors[0].ErrorMessage);
                        if (json.Keys[0].Errors[0].ErrorMessage.trim() != "")
                        {
                            //console.log(json.Keys[0].Errors.ErrorMessage);
                            ShowMssage("e: " + json.Keys[0].Errors[0].ErrorMessage.trim());
                        }
                    }