C# Sharing ValidationContext across different ValidationAttribute fails

662 views Asked by At

Want to apply validation on input model using series of custom validation attributes as mentioned below.

If validation result of first validation attribute ie "ValidatorAttributeOne" is true than no need to process "ValidatorAttributeTwo" validation logic.

To achieve that valid result of "ValidationAttributeOne" assigned to "validationContext.Items" dictionary believing that "validationContext" will share across the different "ValidationAttributes" in same http request but below line always throws below exception

var isDependedFilterValidated = (bool?)validationContext.Items[dependedFilter]

"message": "The given key 'ValidationAttributeOne' was not present in the dictionary.",

public class ValidatorAttributeOne : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
       //custom validation

        validationContext.Items["ValidatorAttributeOne"] = true;
        return ValidationResult.Success;
    }
}


public class ValidatorAttributeTwo : ValidationAttribute
{
    private readonly string dependedFilter = default(string);

    public UsernamesEmailValidatorAttribute()
    {           
    }

    public UsernamesEmailValidatorAttribute(string filter)
    {
        dependedFilter = filter;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var isDependedFilterValidated = (bool?)validationContext.Items[dependedFilter];

        if (isDependedFilterValidated == false)
        {
            //custom validation logic                
        }

        return ValidationResult.Success;
    }
}

public class CustomeModel
{ 
    [ValidatorAttributeOne ]
    [ValidatorAttributeTwo("ValidatorAttributeOne")] 
    public string usernames { get; set; }      
}  
1

There are 1 answers

0
Yiyi You On

Firstly,two custom validation attribute cannot share validationContext,if you don't want to do validationContext when the first one is true.You can set the contents of IsValid method of two validationAttributes together.

For example:

public class ValidationAttributeThree : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            
            if (ValidationAttributeOne IsValid method Content is true) {
                return ValidationResult.Success;
             }
            else if(ValidationAttributeTwo IsValid method Content is true){
               return new ValidationResult("ValidationAttributeOne error message");
            }else{
                return new ValidationResult("ValidationAttributeOne error message"+"ValidationAttributeTwo error message");
            }
                
        }
    }