简体   繁体   中英

JQuery form validation rules syntax

I'm trying to use jquery validation with a rule/message set and can't seem to get it working. Relativeny new to JQuery, so apologies if it's a basic question. I'm trying to use document.forms[0] instead of a form ID. It works with simple validation where the field has class="required" but not if I try to introduce rules. Any help greatly appreciated. Here's the code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://jzaefferer.github.com/jquery-        validation/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $(document.forms[0]).validate({
    rules: {
      cname: {
      required: true,
    }
    },
    messages: {
      cname: "Please enter a valid Name."
    },
  });
  });
  </script>

</head>
<body>


 <form class="cmxform" id="commentForm" method="get" action="">
 <fieldset>
   <legend>A simple comment form with submit validation and default messages</legend>
  <p>
     <label for="cname">Name</label>
     <em>*</em><input id="cname" name="name"/>
   </p>

   <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</body>
</html>

I suppose I'll answer the question since my comment was correct.

Try putting the name attribute as "cname" as well. The validator looks for the name attribute.

Firstly, you can just target your form by its id , #commentForm . Secondly, the root cause of your problem was that you were improperly targeting the input field by its id attribute. However, the .validate() plugin is looking for the name attribute, which in your case, also happened to be "name" . I've changed the value of the name attribute in my example below just to make it more clear.

jQuery:

$(document).ready(function(){
    $('#commentForm').validate({
        rules: {
           username: {
               required: true
           }
        },
        messages: {
           username: "Please enter a valid Name."
        }
    });
});

HTML:

<form class="cmxform" id="commentForm" method="get" action="">

    <input type="text" id="cname" name="username" />

    ....

Working DEMO:

http://jsfiddle.net/egdEn/

See the online documentation for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM