ramb0tn1k
ramb0tn1k

Reputation: 151

jQuery validation plugin. Validation for non form fields?

Ні, all!

I have a little question about jQuery.Validation plugin: - Can I complete validation for input fields that are not form fields (i.e no in the "form" tag) using jQuery.Validation plugin?

Thanks.

Upvotes: 0

Views: 1475

Answers (1)

Sparky
Sparky

Reputation: 98718

Yes you can, but the field still needs to be inside a set of <form> tags. However, you do not need to "submit" this form in order to check validation on the field(s) inside. You use the .valid() method to check this form independently of form submission.

http://jsfiddle.net/9fgVN/13/

<form id="myNonsubmitForm" action="#">
    <textarea name="comments" id="comments" rows="5" cols="30"></textarea>
</form>

<button id="myButton">Click to Check Validation Status</button>
<input type="text" id="output" />

 

$(document).ready(function() {

    $("#myNonsubmitForm").validate({
        validClass: 'valid',  // as per your configuration
        rules: {  // set rules as per your configuration
            comments: {
                required: false,
                maxlength: 10
            }
        },
        errorPlacement: function(error, element) {
             // use this to control placement of error messages
             // removal of errorPlacement handler will result in message appearing next to field automatically.
        }
    });

    $("#myButton").click(function() { // validate on button click for this example
        if($("#myNonsubmitForm").valid()){
            $('#output').val('passed');
        } else {
            $('#output').val('failed');
        };
    });

});

Upvotes: 1

Related Questions