Question

I have written a custom attribute but it does not seem to work client side. It only works on the server when i call the ModelState.IsValid() method. I read somewhere online that i needed to register the custom attribute on the application start method but it was not clear. Please help.

public class MaximumAmountAttribute : ValidationAttribute
    {
    private static string defErrorMessage = "Amount available '$ {0:C}' can not be more than loan amount '$ {1:C}'";
    private string MaximumAmountProperty { get; set; }
    double minimumValue = 0;
    double maximumValue = 0;

    public MaximumAmountAttribute(string maxAmount)
        : base(defErrorMessage)
    {
        if (string.IsNullOrEmpty(maxAmount))
            throw new ArgumentNullException("maxAmount");

        MaximumAmountProperty = maxAmount;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(MaximumAmountProperty);

            if (otherPropertyInfo == null)
            {
                return new ValidationResult(string.Format("Property '{0}' is undefined.", MaximumAmountProperty));
            }

            var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);

            if (otherPropertyValue != null && !string.IsNullOrEmpty(otherPropertyValue.ToString()))
            {
                minimumValue = Convert.ToDouble(value);
                maximumValue = Convert.ToDouble(otherPropertyValue);

                if (minimumValue > Convert.ToDouble(otherPropertyValue.ToString()))
                {
                    return new ValidationResult(string.Format(defErrorMessage, minimumValue, maximumValue));
                }
            }
        }

        return ValidationResult.Success;
    }
}
Was it helpful?

Solution

Creating server side validation with custom validation attribute does not "trasnfer" the validation rules to the client browser (rendering custom javascript validation function).
You will have to write the validation logic as client script too. There are some things you must do:

  1. Make sure the element (input) that has to be validated on the client looks like that:

    <input data-val-MaximumAmount="Validation error massage" />

    The data-val-XXX attribute holding the error message is needed. Html.TextBoxFor is doing the same (adding such attributes to the html elements rendered).

  2. You must create and register client side validation that way:

    (function ($) {
        // Creating the validation method
        $.validator.addMethod('MaximumAmount', function (value, element, param) {
            if (...) // some rule. HERE THE VALIDATION LOGIC MUST BE IMPLEMENTED!
                return false;
            else
                return true;
        });
    
        // Registering the adapter
        $.validator.unobtrusive.adapters.add('MaximumAmount', function (options) {
            var element = options.element,
                message = options.message;
    
            options.rules['MaximumAmount'] = $(element).attr('data-val-MaximumAmount');
            if (options.message) {
                options.messages['MaximumAmount'] = options.message;
            }
        });
    
    })(jQuery);
    
    // Binding elements to validators
    $(function () {
        $(':input[data-val-MaximumAmount]').each(function () {
            $.validator.unobtrusive.parseElement(this, true);
        });
    });
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top