Validating more than one field with Fool Proof

879 Views Asked by At

Hello I'm using MVC Fool Proof Validation. to validate my model, and i need to use RequiredIfNotEmpty with two fields but i'm getting issues with it

Model

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

}

I have tried some like

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

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

But in this case, i can compile, but when i try to use Conex_BT2 i get

'System.NullReferenceException' en FoolproofValidation.dll

Someone know how i must deal with it?

Thanks!

1

There are 1 best solutions below

2
J. Rodríguez On

This question has been answered here:

Foolproof multiple validators on the same fields by Stephen Muecke

The Foolproof.RequiredIfNotAttribute derives from Foolproof.ModelAwareValidationAttribute (which in turn derives from System.ComponentModel.DataAnnotation.ValidationAttribute). ModelAwareValidationAttribute is marked with [AttributeUsage(AttributeTargets.Property)]. Refer source code. By default the the AllowMultiple parameter of AttributeUsage is false which means that you can only apply the attribute once to a property. You have tried to apply it 3 times, hence the error.

Having it true and allowing it to be applied multiple times would possibly cause problems in setting the $.validator.methods and $.validator.unobtrusive.adapters functions used by unobtrusive validation.

You will need to use some other validation attributes or create your own ValidationAtribute that implements IClientValidatable, or rely on server side validation.

You can implement custom validations in the model properties. See this tutorial: Creating Custom Validation Attribute in MVC to create a custom validation attribute to do the work you need, where you should write your own jquery validation script for client side validation in MVC framework mode if using IClientValidatable , which is also explained in it.

Good luck, greetings!