ASP.NET MVC: Client Validation for Custom Attributes

In this post I´ll explain how to validate your custom attributes in the client side. There are two ways to do it, one is when your attribute is inheriting from RequiredAttribute, RegularExpressionAttribute, etc, and the other is when your custom attribute is completely new.

Let´s suppose that you have an IPAddressAttribute to validate IP address, to validate it you just need to check the regular expression, so you create your attribute like this.

public class IPAddressAttribute : RegularExpressionAttribute
{
    public IPAddressAttribute()
        : base(@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
    {
        ErrorMessage = "Invalid IP Address";
    }
}

The server validation will be OK but for client validation works is necessary one more step, open the Global.asax in the the Application_Start add the line below to register the adapter.

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(IPAddressAttribute), typeof(RegularExpressionAttributeAdapter));

What we are doing is using the RegularExpressionAttributeAdapter, it will generate the necessary tags in the element for client validation works.

But what if you create an attribute that doens´t inherits from any other unless the ValidationAttribute?

In this case you need to create the adapter class and the method in javascript. I´ll not show any specific validation, but how to configure it.

Let´s get start creating the custom validation attribute.

public class SomeValidationAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // check if the condition is valid
        return true; // return the result
    }
}

Now we will create the adapter.

public class SomeValidationAttributeAdapter : DataAnnotationsModelValidator<SomeValidationAttribute>
{
    public SomeValidationAttributeAdapter(ModelMetadata metadata, ControllerContext context, SomeValidationAttribute attribute) 
        : base(metadata, context, attribute) { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = "Invalid message.",
            ValidationType = "somevalidation"
        };
    }
}

The ValidationType text is very important, we will reference it in the javascript.

Register the adapter in the Application_Start of the Global.asax.

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(SomeValidationAttribute), typeof(SomeValidationAttributeAdapter));

Now it´s time to configure the javascript, create a new javascript file, reference it below the jquery.validate.js and jquery.validate.unobtrusive.js with the code below.

; (function ($) {
    // somevalidation is the same that the ValidationType of SomeValidationAttributeAdapter
    $.validator.addMethod("somevalidation", function (value, element) {
        var inputValue = $(element).val();
        // check if the condition is valid
        return true; // return the result
    }, jQuery.validator.format("Invalid."));

    // somevalidation is the same that the ValidationType of SomeValidationAttributeAdapter
    $.validator.unobtrusive.adapters.add("somevalidation", function (options) {
        options.rules["somevalidation"] = {};

        if (options.message) {
            options.messages["somevalidation"] = options.message;
        }
    });
})(jQuery);

Now whan you create a ViewModel that has a property with SomeValidationAttribute

public class SomeClass
{
     [SomeValidation]
     public string SomeProperty { get; set; }
}

the validation will happen client and server side.

ASP.NET MVC: Client Validation for Custom Attributes

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Foto do Google

Você está comentando utilizando sua conta Google. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s