jqueryhtmljquery-validate

Not sure why my div is not showing validation messages


I can't seem to figure out why there isn't any text showing in my div after validation of a field. I know that the validation is running but, I'm not sure why my validation message isn't showing up in the div.

Here is my code:

<html>
<head>
    <script src="Scripts/jquery-1.5.2.js" type="text/javascript"></script>
    <script src="http://localhost:62147/Scripts/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">
        "use strict";
        $(document).ready(function () {

            $("#testerbtn").bind("click", function () {
                alert("onclick is fired");
                $("#myform").validate({
                    errorLabelContainer: $("#Errors"),
                    rules: {
                        textToVal: { required: true }
                    },
                    messages: {
                        textToVal: "the field is required! nub~!"
                    }
                });
                alert("validation should have happend.");

            })
        });
        
    </script>
    <title>Test Page</title>
</head>
<body>
    <form id = "myform" action="htmlPage1.htm">
         <div id="Errors"></div>
        <div>
            <input type="text" id="textToVal"  value="" />
            <input type="button" id="testerbtn"  value="Tester" />
        </div>
    </form>
</body>
</html>

Solution

  • There are a couple of things I see here that could be causing issues:

    1. Ensure your inputs have name attributes:

      <input type="text" id="textToVal"  value="" name="textToVal" />
      
    2. validate() should be instantiated outside of your click handler. Additionally, change your button type to submit to automatically trigger the validation code.

    In summary:

    JavaScript:

    $(document).ready(function () {
        $("#myform").validate({
            errorLabelContainer: $("#Errors"),
            rules: {
                textToVal: {
                    required: true
                }
            },
            messages: {
                textToVal: "the field is required! nub~!"
            }
        });
    });
    

    Html:

    <form id = "myform" action="htmlPage1.htm">          
        <div id="Errors"></div>         
        <div>             
            <input type="text" id="textToVal"  value="" name="textToVal" />             
            <input type="submit" id="testerbtn"  value="Tester" />         
        </div>     
    </form>
    

    Working example: http://jsfiddle.net/fJ8XF/