使用Fool Proof验证多个字段

时间:2018-04-19 15:07:27

标签: c# asp.net-mvc-5 model data-annotations foolproof-validation

您好我正在使用MVC Fool Proof Validation.验证我的模型,我需要使用RequiredIfNotEmpty两个字段,但我遇到了问题

模型

public class Conexionado{

    [DisplayName("Conexión")]
    [RequiredIfNotEmpty("Conex_BT2_Pos", ErrorMessage = "Error!")]
    [RequiredIfNotEmpty("Conex_BT2_N", ErrorMessage = "Conex_BT2 Cant be empty if Conex_BT2_N isnt!")]
    public string Conex_BT2 { get; set; }

    public string Conex_BT2_N { get; set; }

    [DisplayName("Ángulo BT")]
    [Range(0, 11, ErrorMessage = "Incorrect number")]
    public int? Conex_BT2_Pos { get; set; }

}

我尝试了一些像

[RequiredIfNotEmpty("Conex_BT2_Pos , Conex_BT2_N", ErrorMessage = "Error!")]

[RequiredIfNotEmpty("Conex_BT2_Pos || Conex_BT2_N", ErrorMessage = "Error!")]

但是在这种情况下,我可以编译,但是当我尝试使用Conex_BT2时,我得到了

  

'System.NullReferenceException'en FoolproofValidation.dll

有人知道我该怎么处理吗?

谢谢!

1 个答案:

答案 0 :(得分:-1)

这个问题已在这里得到解答:

  Foolproof multiple validators on the same fields

Stephen Muecke

Foolproof.RequiredIfNotAttribute派生自Foolproof.ModelAwareValidationAttribute(后者又来自System.ComponentModel.DataAnnotation.ValidationAttribute)。 ModelAwareValidationAttribute标有[AttributeUsage(AttributeTargets.Property)]Refer source code。默认情况下,AllowMultiple的{​​{1}}参数为AttributeUsage,这意味着您只能将属性应用于属性一次。您已尝试将其应用3次,因此出错。

拥有false并允许多次应用可能会导致设置由不引人注意的验证使用的true$.validator.methods函数时出现问题。

您需要使用其他一些验证属性或创建自己的$.validator.unobtrusive.adapters来实现ValidationAtribute,或者依赖服务器端验证。

  

您可以在模型属性中实现自定义验证。请参阅本教程:Creating Custom Validation Attribute in MVC创建自定义验证属性以完成所需的工作,如果使用IClientValidatable,则应在MVC框架模式下编写自己的jquery验证脚本以进行客户端验证,这也在其中进行了说明。

祝你好运,问候!