0

I store values in my web.config. These are settings for the website. For example the event min age limit is 16. I have created my own data annotations to do this and puull back the values using the configurationManager but now I want to create a client side version.

I have this at the moment in a ValidationExtender.js file.

jQuery.validator.addMethod("checkUserAgeOfEvent", function (value, element, param) {
    var dob = $("#DateOfBirth").val();

//do validation here
    if(ConvertToAge(dob) == minAge)
    {
        // do something
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.addBool("checkUserAgeOfEvent");

My problem is that how do I include my value from the web.config or do I have to hard code the min age value? I want to try and avoid this.

tereško
  • 57,247
  • 24
  • 95
  • 149
James Andrew Smith
  • 1,418
  • 2
  • 21
  • 41

1 Answers1

2

I have created my own data annotations to do this

If you implemented the IClientValidatable interface for your custom data annotation you could add custom values to the client as I have illustrated in the following post.

Basically in your GetClientValidationRules method you would pass this minAge to the client:

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = this.ErrorMessage,
        ValidationType = "userage",
    };
    rule.ValidationParameters.Add("minAge", ConfigurationManager.AppSettings["MinAge"]);
    yield return rule;
}

which could be easily retrieved on the client:

jQuery.validator.addMethod(
    "checkUserAgeOfEvent", 
    function (value, element, params) {
        var dob = $("#DateOfBirth").val();
        var minAge = params.minAge;
        if(ConvertToAge(dob) == minAge) {
            // do something
        }
        return true;
    }
);
Community
  • 1
  • 1
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902