如何在jquery.serialize()中验证每个参数?

时间:2012-11-05 03:12:32

标签: jquery validation serialization

我的表格如下:

<form id="gb">
  <div><input type="text" name="a" value="" /></div>
  <div><input type="text" name="b" value="" /></div>
<div><input type="submit" name="s" value="Submit" /></div>
</form>

我使用jquery.serialize()方法进行序列化:

$('form#gb').submit(function() {
  $catch = $(this).serialize();

  /* This produces a query string: 
  a=XXXX&b=XXXXX */

  ...
  /* i want to validate a & b here */
  ...

  $.ajax({
     /* My Ajax Code */
  });

});

我想验证一个&amp;在ajax动作之前的b值,怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用serializeArray().

  

.serializeArray()方法创建一个JavaScript对象数组,   准备编码为JSON字符串。它在jQuery对象上运行   表示一组表单元素

答案 1 :(得分:1)

始终进行服务器端验证。这就是说,如果你想在服务器端验证之前添加客户端验证,请检查这个jquery验证插件。 http://docs.jquery.com/Plugins/Validation#Example

的Javascript

$(document).ready(function(){
    $("#commentForm").validate({submitHandler: function(form) {
        // some other code
        // maybe disabling submit button
        // then:
        $.ajax({
             /* My Ajax Code */
        });
    });
});

HTML

<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" size="25" class="required" minlength="2" />
    </p>
    <p>
    <label for="cemail">E-Mail</label>
    <em>*</em><input id="cemail" name="email" size="25"  class="required email" />
    </p>
    <p>
    <label for="curl">URL</label>
    <em>  </em><input id="curl" name="url" size="25"  class="url" value="" />
    </p>
    <p>
    <label for="ccomment">Your comment</label>
    <em>*</em><textarea id="ccomment" name="comment" cols="22"  class="required"></textarea>
    </p>
    <p>
    <input class="submit" type="submit" value="Submit"/>
    </p>
    </fieldset>
</form>
相关问题