How to re-use multiple data annotations for multiple properties

I want to use the following data annotations:

[RegularExpression(@"^\d+\.\d{0,2}$", ErrorMessage = "Invalid price entered, please re-check the price and try again.")]
[Range(0, 999999.99, ErrorMessage = "The price must be less than £999999.99")]

For all price properties in my classes but I do not want to have to reuse the annotations and want to combine them into, for example, [PriceValidation] and print this above all properties.
Can this be done? TIA

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can create own custom validation attribute which will incapsulate needed logic. Something like this for starters:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class PriceValidationAttribute : ValidationAttribute
{
    private static readonly Regex Regex = new Regex(@"^\d+\.\d{0,2}$", RegexOptions.Compiled);

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
        if (stringValue != null && !Regex.IsMatch(stringValue))
        {
            return new ValidationResult("Invalid price entered, please re-check the price and try again.");
        }

        var doubleValue = Convert.ToDouble(value);
        if (doubleValue > 999999.99 || doubleValue < 0)
        {
            return new ValidationResult("The price must be less than £999999.99");
        }
        
        return ValidationResult.Success;
    }
}

Also you can look into using fluent validation library.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply