I'm trying to pass a boolean parameter from the 'GetClientValidationRules' method of a validator. However the parameter comes through as a string. Is it possible to pass the parameter as an actual boolean value?
Code for reference:
Server-side:
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule()
{
ErrorMessage = "This is an error."
ValidationType = "test"
}
rule.ValidationParameters.Add("test", true);
yield return rule;
}
Client-side:
$.validator.unobtrusive.adapters.add("test", ["test"], function(options) {
var parameter = options.params.test;
if (parameter) { // Always true, because parameter === "True" (string value)
...
}
});
I understand that i could just use 'if (parameter === "True")' but would like to avoid doing so if possible.
Any help would be greatly appreciated.
Unfortunately all values are passed as strings, so you'll have to parse it there.
However, you can pass it to the validation method as a boolean:
$.validator.unobtrusive.adapters.add("test", ["test"], function (options) {
var parameter = options.params.test;
options.rules["myMethod"] = parameter.toLowerCase() === "true";
// add other options, such as the validation message
});
$.validator.addMethod("myMethod", function (value, element, params) {
// 'params' would be the boolean value 'true'
});