Validating multiple textboxes using JqueryValidati

2019-08-26 11:48发布

问题:

Iam rendering partial a view twice on the same parent view.Since each child view has 1 textbox each I have 2 textboxes. Iam trying to use JqueryValidation Plugin as in

$("#form0").validate({ 
    rules: {
    Address<%=Model.TypeName%>: { 
            required: true, 
            minLength: 8 

        } }, 
    messages: {

    Address<%=Model.TypeName%>: : { 
            required: "Please enter an address", 
            minLength: "Your address must consist of at least 8 characters" 

        } 
    } 

I have two Model.TypeNames , 1) student, 2) parent.

When I try to validate both the textboxes( 1 for student, 1 for parent) , only the 1st one works. the second one doesnot validate. Any ideas/suggestions to make the validation work for both the textboxes would be highly appreciated.

回答1:

The jquery validate plugin works by providing rules for input fields given their names. You will need to provide both inputs when specifying your rules. Another possibility is to do the following. Include validation once:

$("#form0").validate({ });

and then add rules dynamically:

$('input[name=Address<%=Model.TypeName%>]').rules('add', {
    required: true,
    minlength: 8,
    messages: {
        required: 'Please enter an address',
        minlength: 'Your address must consist of at least 8 characters'
    }
});

Because you are including two partials you will end up with two calls to the .rules('add' function for both input fields.