有什么办法第一次失败后停止DataAnnotation验证? [英] Is there any way to stop DataAnnotation validation after the first failure?

查看:85
本文介绍了有什么办法第一次失败后停止DataAnnotation验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ViewModels我用几个DataAnnotations验证表单数据,通常有2-3个字段注释。

In my ViewModels I use several DataAnnotations to validate the form data, there are usually 2-3 annotations per field.

例如一个电子邮件地址字段可能是这样的:

For example a field for an email address might look like this:

[Required(ErrorMessage = "Please enter an email address.")]
[Email(ErrorMessage = "That is not a valid email address.")] // Custom
public string Email { get; set; }

现在如果有人提交表单,这两个错误将在验证摘要显示出来。有没有简单的方法来指定要运行验证注解,以便在需要的验证失败,电子邮件验证不跑?

Now if someone were to submit the form, both errors would show up in the validation summary. Is there any easy way to specify an order to run the validation annotations so that if the Required validation fails, the Email validation doesn't run?

如果这是不可能的,这是怎么通常处理?我是否应该创建自定义的验证程序具有比单一注解更多的领域呢?请问这是否使用注释有道,在一个单一的手柄之一验证多种类型的?

If this isn't possible, how is this usually handled? Should I create custom validators for any field that has more than a single annotation? Would that be a proper way to use annotations, where a single one handles multiple types of validation?

(我也知道我大概可以结合必需标注到定制的电子邮件,但是这仅仅是一个例子)。

(I'm also aware I could probably combine the Required annotation into the custom Email one, but this is just an example).

推荐答案

在这种特殊情况下,我可能会采取同样的做法是,ASP.NET的WebForms验证拿 - 只要有 EmailAttribute 校验符真正如果值为或空。

In this specific case I would probably take the same approach that the ASP.NET WebForms validators take - simply have the EmailAttribute validator return true if the value is null or empty.

想想吧:


  • 如果需要的电子邮件地址,然后还会有一个 [必需] 验证器和一个空/空的电子邮件地址会生成一个验证错误无妨;

  • If the e-mail address is required, then there will also be a [Required] validator and a null/empty e-mail address will generate a validation error anyway;

如果电子邮件地址是可选的,空/空值应被视为有效。

If the e-mail address is optional, a null/empty value should be considered valid.

没有需要解决拦截验证的复杂的问题时,你可以设计出单独的验证发挥好起来!

No need to solve the complex problem of intercepting validators when you can just design the individual validators to play nice together!

这篇关于有什么办法第一次失败后停止DataAnnotation验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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