0
votes

I need to insert a custom value into the errormessage for the required attribute as in say

there is a property property decimal WagePaid

and there is another property in the same entity property string Month

Then the error message when WagePaid is not provided should be, Please enter the wage paid for the month of January.

Is the required attribute capable of doing this or what customization should be done to achieve this

1
The error messages associated with validation attributes are static and jquery-validate-unobtrusive parses them when the page is first loaded. You could possibly have a script to change the ``data-val-required` attribute of WagePaid based on the current month and then re-parse the validator. - user3559349

1 Answers

0
votes

I would implement IValidatableObject.

public class ClassWhichNeedsValidation : IValidatableObject
{
    public string Month {get; set;}
    public decimal WagePaid{get; set;}

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
            if (WagePaid == null)
                yeild return new ValidationResult("Please enter the wage paid for the month of January.")
    }
}

Or you can write your custom Validation Attribute and apply it on the desired property like this:

[CustomValidation("Month")]
public decimal WagePaid{get; set;}

public class CustomValidationAttribute : ValidationAttribute
{
    public CustomAttribute(string month)
    {
        _month = month;
    }
    private string _month;

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var property = context.ObjectType.GetProperty(propertyName);
        var monthValue = property.GetValue(context.ObjectInstance, null);

        if (value == null)
        {

            return new ValidationResult("Please enter the wage paid for the month of " + monthValue);
        }
        return null;
    }
}