Huntwer
Huntwer

Reputation: 121

jQuery Validation this.optional is not a function

I created my own custom validation method which uses the minlength method in turn, however I get this error:

this.optional is not a function

My code is here:

jQuery.validator.addMethod("validAccount", function(value, element, params) {
        var res = true;
        if (!isNaN(parseInt(value[0]))) {
            res = false;
        } else if (!$.validator.methods.minlength(value.split(""), element, params)) {
            res = false;
        }
        return res;
    }, "The inserted account isn't valid");

Can anyone help me? I want understand where the problem is.

Note: In the minlength method I use split because without it I also get getLength is not a function.

Upvotes: 0

Views: 387

Answers (1)

Sparky
Sparky

Reputation: 98738

Quoting OP's comment:

"The account field shouldn't start for a number, there is no such built-in method. So I should create it. Also, the account field should be at least n characters. I thought about using the existing method for this instead of re-created it, but I see that this is a bad idea."

Perhaps you didn't know you can apply several rules to the same field at once. You can write a custom rule that says it should not start with a number, and then use it alongside the default minlength rule.

$("#idform").validate({
    rules: { 
        account: { 
            validAccount: true, // <- custom rule to make sure does not start with number
            minlength: 4        // <- default rule (at least 4 characters entered)
        } 
    }
});

You can use as many default and/or custom rules (methods) as you need. Also, check out the additional-methods.js file for even more.

Upvotes: 1

Related Questions