jQuery验证:一些必填字段未填写,但仍可以提交表单 [英] jQuery validation: some of the required field not filled but the form can still be submitted

查看:581
本文介绍了jQuery验证:一些必填字段未填写,但仍可以提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了jquery验证( http://bassistance.de/jquery-plugins/jquery-plugin-validation/)进行表单验证.以下是我的代码的一些片段:

I used jquery validation (http://bassistance.de/jquery-plugins/jquery-plugin-validation/) for form validation. The followings are some fragments of my code:

HTML:

<form id="formID" action="/processForm" method="post">
  ...
  <input id="name" type="text" name="name" size="10" />
  <input id="username" type="text" name="username" size="10" />
  ...
<input type="submit" value="Submit" />

jQuery:

$("#formID").validate({
  onkeyup:false,

  rules: {
    name: {required: true},
    username: {required: true, checkUsername: true}
    ...
  },
  messages: {
    name: {required: "Must fill"},
    username: {required: "Must fill", checkUsername: "Username unavailable"},
    ...
  }

});

// Check if username exists
$.validator.addMethod('checkUsername', function(username) {
  var postURL = "/checkUsername";
  $.ajax({
    ...
  });
  return ...;
}, '');


// Submit the form by Ajax
$(document).ready(function() {
  $('.formID').ajaxForm({
    success: function(returnData) {
      $('#content').html(returnData);
    }
  });
});

奇怪的是,我可以将某些必填字段保留为空白或未选中,并且仍可以提交表单.如果保留空白,则某些必填字段会阻止提交,而其他字段则不能.有人遇到过同样的奇怪问题吗?还是我在这里做错了什么?

Something odd is that I can leave some of the required fields blank or unchecked, and the form can still be submitted. Some required fields can prevent from submitting if left blank, but others don't. Did anybody encounter the same strange problem? Or did I do anything wrong here?

顺便说一句,如果我单击提交按钮时未填写任何内容,则所有必填字段均正确显示错误消息.但是其中一些只是不会阻止表单被提交.请帮忙.

BTW, if I click the submit button without filling anything, all required fields show error messages correctly. But some of them just won't prevent the form from been submitted. Please help.

底部的Ajax表单提交功能似乎不起作用.我该如何纠正?

The Ajax form submission function at the bottom doesn't seem to work. How do I correct it?

推荐答案

总结一下,为了同时使用表单验证和Ajax提交,请将'submitHandler'添加到validate()函数中:

Summing up, in order to employ both form validation and ajax submission, add 'submitHandler' to the validate() function:

$("#formID").validate({
  onkeyup:false,

  rules: {
    ...
  },

  messages: {
    ...
  },

  // Submit the form
  submitHandler: function(form) {
    theUrl = '/processData';
    var params = $(form).serialize();
    $.ajax ({
      type: "POST",
      url: theUrl,
      data: params,
      processData: false,
      async: false,
      success: function(returnData) {
        $('#content').html(returnData);
      }
    });
  }

});

这篇关于jQuery验证:一些必填字段未填写,但仍可以提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆