为什么仅在属性验证通过的情况下才调用IValidatableObject.Validate? [英] Why is IValidatableObject.Validate only called if property validation passes?

查看:67
本文介绍了为什么仅在属性验证通过的情况下才调用IValidatableObject.Validate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中,似乎Validate()仅在两个属性均通过验证之后才被称为.

In my model, it seems that Validate() is only called AFTER both properties pass validation.

public class MyModel : IValidatableObject 
{
    [Required]
    public string Name { get; set;}

    [Required]
    public string Nicknames {get; set;}

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Nicknames != null && Nicknames.Split(Environment.NewLine.ToCharArray()).Count() < 2)
            return yield result new ValidationResult("Enter at least two nicknames, new [] { "Nicknames" });
    }
}

当用户在Nicknames文本区域中输入单行文本,但将Name文本框保留为空时,仅显示Name属性的Required错误消息.应该从Validate()函数显示的错误消息永远不会出现.

When a user enters a single line of text in the Nicknames text area but leaves the Name text box empty, only the Required error message for the Name property is displayed. The error message that should be displayed from the Validate() function never shows up.

仅在Name文本框中输入名称并在Nicknames文本中输入一些文本之后,才会调用Validate()函数.

Only after entering a name in the Name text box and some text in the Nicknames text is the Validate() function called.

这是应该如何工作的吗?在当前页面上引起错误时,在下一页上向用户显示错误消息似乎很奇怪.

Is this how it's supposed to work? It seems odd that a user is shown an error message on a subsequent page when the error is being caused on the current page.

推荐答案

这是设计使然.在所有属性均通过验证之前,不会触发对象级验证,因为否则,对象可能不完整. Validate方法用于将一个属性与另一个属性进行比较.在您的情况下,您应该编写一个自定义属性验证器.

This is by design. Object-level validation does not fire until all the properties pass validation because otherwise it is possible that the object is incomplete. The Validate method is meant for thing like comparing one property to another. In your case you should write a custom property validator.

这篇关于为什么仅在属性验证通过的情况下才调用IValidatableObject.Validate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆