Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: PropertyValidator - Create a BaseValidation class for custom error messages

$
0
0

I just found a trick and it seems to be working well.

 

public BaseValidation(CustomProperty property)
            : base("{ErrorMessage}")
        {
            this.property = property;
        }

And now where the magic happens:

protected override bool IsValid(PropertyValidatorContext context)
        {
            if (!property.Visible) // if the field is not visible we make it valid
                return true;

            if (property.Mandatory)
            {
                if (context.PropertyValue == null)
                {
                    if (string.IsNullOrEmpty(context.PropertyValue.ToString()))
                    {
                        context.MessageFormatter.AppendArgument("ErrorMessage", string.Format("The field {0} is mandatory", property.DisplayName));
                        return false;
                    }
                }
            }

            if (context.PropertyValue.ToString().Length < property.MinValue)
            {
                context.MessageFormatter.AppendArgument("ErrorMessage", string.Format("The field {0} must be between {1} and {2} characters.", property.DisplayName, property.MinValue, property.MaxValue));
                return false;
            }
            return true;
        }

Not sure if it's the best way, but it's working as I wanted.

 

Thanks.


Viewing all articles
Browse latest Browse all 1917

Trending Articles