0

I am using the validate plugin for jquery and have the following custom method:

$.validator.addMethod("username", function(value, element) {
    if (element.prop("required")) {  
        var re = new RegExp('^([FG]?\\d{5}|\\d{5}[AB])$');
    } else  {
        var re = new RegExp('^'+element.defaultValue+'|^([FG]?\\d{5}|\\d{5}[AB])$');
    }
    return re.test(value);
});

The if statement returns the error element.prop is not a function.

I've also tried $(this).prop... and although I don't get any errors it always runs the else part of the statement.

Is there anything else I can use instead to achieve this??

EDIT:

Here's the call:

$("#myform").validate({
    debug: true,
    ignore: ".ignore",
    rules: {
        field: {
            required: {
                 depends: function() {
                     return $(this).prop("required");
                 }
            },
            username: true,
        }
    },
    messages: {
        field: {
            username: "Enter a valid username"
        }
    },
    success: function(label) {
        label.text("Good result!");
    },
    submitHandler: function() {
        alert("submitted!");
    }
});
0

2 Answers 2

2

I think you should use:

if ($(element).prop("required")) { 
Sign up to request clarification or add additional context in comments.

3 Comments

Ha! As much as I thought I'd tried everything, I guess I missed this one. Thanks!
That is often the case - you did almost try this exact answer, but not quite :)
@Tom: If you don't want to wrap the element into a jQuery object you can also use element.getAttribute("required"), though if you are using jQuery anyways, then there is no need to mix syntax.
0

you may be using older jQuery version:

try $(element).attr("required")

2 Comments

try $(element).attr("required")
@RajeevSharma: You should update your answer with your comment $(element).attr("required") as element.attr("required") is not going to execute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.