user520300
user520300

Reputation: 1527

jquery error message place in div (jquery.validate.js)

I have the following script which validates pages using jquery.validate.js through a quiz and works perfectly. Im looking to have the error message for required fields to be placed into a div called errormessage. jQuery validate usually returns a message "this field is required".

Here is the script

<script type="text/javascript">
var curPage=1;
function NextPage() {
    if (curPage < <?= $num; ?>) {
        var group = "#page_" + curPage.toString();
        var isValid =true;
         $(group).find(':input').each(function (i, item) {
              if (!$(item).valid())
                isValid = false;
            });

        if( !isValid){ alert("PLEASE MAKE A SELECTION"); }
        else{
            $("#page_" + curPage.toString()).hide(); //hide current page div
            curPage++;  //increment curpage
            $("#page_" + curPage.toString()).show(); //show new current page div
        }
    }
}
 function PrevPage() {

     if (curPage > 1) {
         $("#page_" + curPage.toString()).hide(); //show new current page div
         curPage--;  //increment curpage
         $("#page_" + curPage.toString()).show(); //hide current page div
     }
 }

 function InitializePage() {
     $(".wizardPage").hide();
     $("#page_" + curPage.toString()).show();


     $("#surveyForm").validate({onsubmit: false});

 }




 $(document).ready(InitializePage
    );
</script>

Upvotes: 0

Views: 2085

Answers (2)

Jasper Mogg
Jasper Mogg

Reputation: 924

Switch this line - $("#surveyForm").validate({onsubmit: false}); out for the following -

$("#surveyForm").validate({
    rules: {
    xyz: {
        required: true
    }
},
messages: {
    xyz: {
    required: $('div#errormessage').append("xyz is a required field!");
    }
}
}, onsubmit: false)

It will check if xyz is filled or not. If not, it'll put xyz is a required field! in a div with id errormessage.

For more details about rules, check out this page. Scroll down until you get to 'rules'.

The above code, by putting in rules for each field, will allow you to specify different locations for each error message. The blog post in spider's answer contains a simpler way of doing things, and is therfore preferable if you don't require this customisability.

Upvotes: 0

Bogdan
Bogdan

Reputation: 44586

Try setting up the error container element like explained here:

http://mitchlabrador.com/2010/11/05/how-to-change-the-way-jquery-validate-handles-error-messages/

Upvotes: 1

Related Questions