Prasad
Prasad

Reputation: 59491

show jquery validation error below the element

I have two elements(dropdowns) which are very closely placed. These elements are required fields.

I am using jquery valiate to validate the fields. The error message are showing for both the elements and the space between the elements increases as the error message of first control is displayed near the element

$('#RegisterForm').validate({
        rules: {
            Country:{required: true},
            State:{required: true}
        },
        messages: {
            Country:{required: "Select Country"},
            State:{required: "Select State"}
        }
    });

I have tried using break before the elements as:

$('#RegisterForm').validate({
            rules: {
                Country:{required: true},
                State:{required: true}
            },
            messages: {
                Country:{required: "<br/>Select Country"},
                State:{required: "<br/>Select State"}
            }
        });

When i did so, the second element moves to next line.

How can i show the error messages just below the elements without affecting the alignment/placement of nearby elements.

Upvotes: 10

Views: 17192

Answers (2)

feelimann
feelimann

Reputation: 1

Found a solution using InsertAfter() method on my aspx webform:

jQuery(function () {

//Do the Validation! Specify wrap element, add style, class and insert error message after element by ID

$('#yourform').validate({
    wrapper: 'span',
      errorPlacement: function (error, element) {
        error.css({ 'color': '#FFA500', 'font-size': '0.750em' });     
        error.addClass("error")
        error.insertAfter($('[id*=element_before_error_message]'));
    }
});

//Applying rules

$('[id*=element_to_validate]').rules('add', {

   required: true,
   messages: {
   required: '<br />* Some Validation Text'
    }
});

});

Upvotes: 0

Guillaume Flandre
Guillaume Flandre

Reputation: 8980

Use the errorPlacement option (see documentation here: http://docs.jquery.com/Plugins/Validation/validate#toptions)

$('#RegisterForm').validate({
        rules: {
            Country:{required: true},
            State:{required: true}
        },
        messages: {
            Country:{required: "Select Country"},
            State:{required: "Select State"}
        },
        errorPlacement: function(error, element) {
            error.appendTo( element.parent("td").next("td") );
        }
    });

Of course you'll have to adapt the code to your situation.

Upvotes: 16

Related Questions