如何在异步提交form的时候利用jQuery validate实现表单验证

如题所述

<?php if(isset($_GET['act']) && $_GET['act']=='valid'){
$username=$_REQUEST['username'];
echo json_encode($username);
}else{?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
  $("#myform").validate({
    rules: {
      username: {
        required: true,
        rangelength:[2,6]
      }
    },
    messages: {
      username: {
        required: "请输入姓名",
        rangelength:$.validator.format("姓名最小长度:{0}, 最大长度:{1}。")
      }
    },
submitHandler:function(form){
$.ajax({
url:"?act=valid",
type:"POST",
data:$(form).serialize(),
dataType:"json",
success: function(data){
//console.log(data);
alert('提交成功');
$('#username').val('');
}
});
}
  });
});
</script>
</head>

<body>
<form id="myform">
  <fieldset>
    <legend>验证表单</legend>
    <p>
      <label for="username">姓名</label>
      <input id="username" name="username" type="text" />
    </p>
    <p>
      <input class="submit" type="submit" value="提交" />
    </p>
  </fieldset>
</form>
</body>
</html>
<?php }?>

温馨提示:内容为网友见解,仅供参考
第1个回答  2017-11-07
onError后面函数再添加一句阻止提交数据的代码试试。
相似回答