Luke
Luke

Reputation: 443

MVC Client Side Validator - passes boolean as a string

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.

Upvotes: 0

Views: 561

Answers (2)

Will Ray
Will Ray

Reputation: 10879

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'
});

Upvotes: 1

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

The default boolean parsing methods like !!(parameter) or Boolean(parameter) may not working properly here since it always returns true if parameter contains any kind of strings, hence you need an additional function returning Boolean to parse it properly:

function parseBoolean(value) {
    // return value.toString().toLowerCase() === "true" also work here
    return String(value).toLowerCase() === "true";
}

Then, Will Ray's code should be modified to use that function shown below:

$.validator.unobtrusive.adapters.add("test", ["test"], function (options) {
    var parameter = options.params.test;

    // parse as boolean value here
    options.rules["myMethod"] = parseBoolean(parameter);

    // add other options, such as the validation message
});

$.validator.addMethod("myMethod", function (value, element, params) {
    // 'params' would be the boolean value 'true'
});

Upvotes: 1

Related Questions