1

对于多个必填字段的简单验证,我正在使用此处解释的自定义验证器

我得到了所需的行为并且验证摘要消息正确显示,但我现在缺少的是无效输入元素上缺少验证错误 css 类,这是在使用内置验证器时添加的。

这是正确的行为:

<input class="input-validation-error" name="ModelName" ... />

这就是我在使用提到的自定义验证器时得到的:

<input name="ModelName" ... />

请注意,我指的是服务器端验证。

更新

这是我的模型:

public class Register
{
        [MultiFieldRequired(new[] { "Name", "UserName" }, ErrorMessage = "Please provide all required information")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [MultiFieldRequired(new[] { "Name", "UserName" }, ErrorMessage = "Please provide all required information")]
        [Display(Name = "User name")]
        public string UserName { get; set; }
}

这是渲染的输出:

<input class="text-box single-line" data-val="true" data-val-multifield="Please provide all required information" id="Name" name="Name" type="text" value="" />
<input class="text-box single-line" data-val="true" data-val-multifield="Please provide all required information" id="UserName" name="UserName" type="text" value="" />

我现在意识到只有当我使用MultiFieldRequired属性装饰整个模型类时才会出现问题:

[MultiFieldRequired(new[] { "Name", "UserName" }, ErrorMessage = "Please provide all required information")]
public class Register
{
...

在这种情况下,没有无效字段修改了 css 类,而在另一种情况下,当我注释模型中的每个字段时,我得到相同的错误消息乘以无效字段的数量。

因此,总而言之 - 无论无效字段的数量如何,我都希望有一条错误消息,并且我还希望每个无效字段都用 .input-validation-error 类标记。

4

2 回答 2

2

我刚刚对此进行了测试,它工作正常。这是我所做的:

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(IndexModel model)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("NextAction");
        }
        return View(model);
    }
}

模型:

public class IndexModel
{
    [MultiFieldRequiredAttribute(new string[] { "AreaCode", "PhoneNumber" })]
    public string AreaCode { get; set; }

    [MultiFieldRequiredAttribute(new string[] { "AreaCode", "PhoneNumber" })]
    public string PhoneNumber { get; set; }
}

我完全按照示例中提供的方式使用了验证:

public class MultiFieldRequiredAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string[] _fields;

    public MultiFieldRequiredAttribute(string[] fields)
    {
        _fields = fields;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        foreach (string field in _fields)
        {
            PropertyInfo property = validationContext.ObjectType.GetProperty(field);
            if (property == null)
                return new ValidationResult(string.Format("Property '{0}' is undefined.", field));

            var fieldValue = property.GetValue(validationContext.ObjectInstance, null);

            if (fieldValue == null || String.IsNullOrEmpty(fieldValue.ToString()))
                return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }

        return null;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "multifield"
        };
    }
}

看法:

@model IndexModel

@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.AreaCode)
    @Html.EditorFor(m => m.PhoneNumber)
    <input type="submit" value="submit" />
}

如果您随后显示该视图,则会为区号显示以下内容:

<input class="text-box single-line" data-val="true" data-val-multifield="" id="AreaCode" name="AreaCode" type="text" value="" />

如果您然后单击提交按钮,您将获得以下信息:

<input class="input-validation-error text-box single-line" data-val="true" data-val-multifield="" id="AreaCode" name="AreaCode" type="text" value="" />

当您单击添加的提交按钮时input-validation-error

于 2012-05-18T13:49:32.917 回答
1

我期待视图中的无效字段将用.input-validation-error类标记,而不管属性的位置,所以我使用自定义验证器属性来注释我的模型类,如下所示:

[MultiFieldRequired(new[] { "Name", "UserName" }, ErrorMessage = "Please provide all required information")]
public class Register
{
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Display(Name = "User name")]
        public string UserName { get; set; }
}

另一方面,如果我注释每个字段:

public class Register
{
        [MultiFieldRequired(new[] { "Name", "UserName" }, ErrorMessage = "Please provide all required information")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [MultiFieldRequired(new[] { "Name", "UserName" }, ErrorMessage = "Please provide all required information")]
        [Display(Name = "User name")]
        public string UserName { get; set; }
}

我的视图在验证摘要中生成多个相同的消息。

所以我最终使用ValidationSummary得到了一个自定义验证摘要错误消息,如下所示:

@Html.ValidationSummary(true, "Please provide all required information")

我的字段用简单的星号装饰,如下所示:

public class Register
{
        [Required(ErrorMessage = "*")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "*")]
        [Display(Name = "User name")]
        public string UserName { get; set; }
}

最后,我的视图呈现如下:

验证错误消息

高温高压

于 2012-05-21T11:56:50.860 回答