locked
How to get client side validation RRS feed

  • Question

  • User-648361319 posted

    Hi,

    i have a class that i am overriding.

    public partial class MasterOverride : Master
        {
           [NumbericValidationAttribute]
            public override string Name { get; set; }
        }
    
    public class NumbericValidationAttribute : ValidationAttribute 
        { 
            public NumbericValidationAttribute() 
                : base() 
            { 
     
            } 
            public override bool IsValid(object value) 
            { 
                Regex objIntPattern = new Regex(@"^[0-9]{8}$"); 
                return !objIntPattern.IsMatch(value.ToString()); 
            } 
        }

    The validation is working properly at server side but not on client side. How to do this... ?

    Wednesday, July 6, 2011 12:54 PM

Answers

  • User1904378495 posted

    Custom validation rules that inherit from ValidationAttribute don't automatically get client side validation. That's because the validation code isn't automatically serialized to javascript. However, you can get client side validation working, you just have to do a little bit of work and write some client side code to do it.

    First thing you have to do to get custom client validation is to have your validation attribute implement IClientValidatable,  then you create modelType key server side. Finally you have to write custom javascript that adds an adapater to the jquery validation and checks for that key and performs javascript validation when the framework gives it that key.

    Take a look at this blog post. It does a good job explaining how all this works and has code samples.
    http://www.jacopretorius.net/2011/01/client-side-validation-in-mvc-3.html
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 6, 2011 1:28 PM
  • User-474980206 posted

    you can use the unobtrusive validation if you want to use your attributes. first read and understand the jquery validation plugin and its rule model. instead of class names, unobtrusive validation uses html 5 data-* attributes to tie a rule to a field. at startup it gets all [data-val="true"] elements and calls the jquery plugin to hookup. now to add suppport for a new rule, you add the rule to validation, see $.validator.addMethod(). tell the ms layer about the new rule see, $.validator.unobtrusive.adapters.addBool(). now you have the client framework setup. try something like:

    $.validator.addMethod('numberic',
       function (value, element, params) {
          return /^[0-9]{8}$/.test($(element).val());
       },
       'This field is a 8 digit numeric.'
    );
    $.validator.unobtrusive.adapters.addBool('numberic');

    then you need to tell the server to generate the proper rules. change your validator to implement IClientValidatable, which just return a simple collection of rule names/error messages. something like:

    public class NumbericValidationAttribute : ValidationAttribute, IClientValidatable
    { 
        static Regex rxIntPattern = new Regex(@"^[0-9]{8}$"); // compile only once
        public override bool IsValid(object value) 
        { 
            return rxIntPattern.IsMatch(value.ToString()); 
        } 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                 ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                 ValidationType = "numberic"
            };
        }
    }
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 6, 2011 1:37 PM

All replies

  • User-1166080021 posted

    Hi friend,

    maybe this post can help you!

    Good Luck!

    Wednesday, July 6, 2011 12:59 PM
  • User-648361319 posted

    actually i am not using any metadata

    I am overriding existing class with virtual 

    Wednesday, July 6, 2011 1:24 PM
  • User1904378495 posted

    Custom validation rules that inherit from ValidationAttribute don't automatically get client side validation. That's because the validation code isn't automatically serialized to javascript. However, you can get client side validation working, you just have to do a little bit of work and write some client side code to do it.

    First thing you have to do to get custom client validation is to have your validation attribute implement IClientValidatable,  then you create modelType key server side. Finally you have to write custom javascript that adds an adapater to the jquery validation and checks for that key and performs javascript validation when the framework gives it that key.

    Take a look at this blog post. It does a good job explaining how all this works and has code samples.
    http://www.jacopretorius.net/2011/01/client-side-validation-in-mvc-3.html
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 6, 2011 1:28 PM
  • User-474980206 posted

    you can use the unobtrusive validation if you want to use your attributes. first read and understand the jquery validation plugin and its rule model. instead of class names, unobtrusive validation uses html 5 data-* attributes to tie a rule to a field. at startup it gets all [data-val="true"] elements and calls the jquery plugin to hookup. now to add suppport for a new rule, you add the rule to validation, see $.validator.addMethod(). tell the ms layer about the new rule see, $.validator.unobtrusive.adapters.addBool(). now you have the client framework setup. try something like:

    $.validator.addMethod('numberic',
       function (value, element, params) {
          return /^[0-9]{8}$/.test($(element).val());
       },
       'This field is a 8 digit numeric.'
    );
    $.validator.unobtrusive.adapters.addBool('numberic');

    then you need to tell the server to generate the proper rules. change your validator to implement IClientValidatable, which just return a simple collection of rule names/error messages. something like:

    public class NumbericValidationAttribute : ValidationAttribute, IClientValidatable
    { 
        static Regex rxIntPattern = new Regex(@"^[0-9]{8}$"); // compile only once
        public override bool IsValid(object value) 
        { 
            return rxIntPattern.IsMatch(value.ToString()); 
        } 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                 ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
                 ValidationType = "numberic"
            };
        }
    }
    
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 6, 2011 1:37 PM
  • User-648361319 posted

    It's not a fixed regex, depends on user i have to check with different regex...

    Thursday, July 7, 2011 1:21 AM