【问题标题】:Custom ValidationResult in model Asp.net mvc模型 Asp.net mvc 中的自定义 ValidationResult
【发布时间】: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


【解决方案1】:

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

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());
                        }
                    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多