Jquery 表单提交验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13541133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:42:38  来源:igfitidea点击:

Jquery form submit validation

jqueryvalidationjqxwidgets

提问by edaklij

I have following form:

我有以下表格:

<form id="testForm" action="country_Save">
   Country Name:<input type="text" id="countryName" />  
   <input type="submit" id='saveCountry' value="Add Country" />
</form>

and following JQuery for validating textfield

并遵循 JQuery 验证文本字段

$('#testForm')
   .jqxValidator({  rules : [
          {
              input : '#countryName',
              message : 'Country Name is required!',
              action : 'keyup, blur',
              rule : 'required'
          }],
          theme : theme
});

How can i use this validation when I am submitting a form?

提交表单时如何使用此验证?

采纳答案by Gajotres

Try this please:

请试试这个:

     $('#testForm').on('submit', function() {
         return $('#testForm').jqxValidator('validate');
     });

回答by Soumya

Bind a function to the submitevent of the form. Return falsein this function if any of the form fields fail validation.

将函数绑定到submit表单的事件。false如果任何表单字段验证失败,则返回此函数。

For example:

例如:

$('form').on('submit', function() {
    // do validation here
    if(/* not valid */)
        return false;
});

回答by Peter Krauss

Form validationhave a wide set of Javascript and jQuery libraries... My sugestion is a simple jquery.com plugin.

表单验证有大量的 Javascript 和 jQuery 库...我的建议是一个简单的jquery.com 插件

PS: jqxValidatoris a method from the jQWidgets framework? if you (reader) not need so heavy/complex plugin, see bellow pure jQuery, else @Gajotres writed the best solution (!).

PS: jqxValidator是来自jQWidgets 框架的方法吗?如果您(读者)不需要如此沉重/复杂的插件,请参阅下面的纯 jQuery,否则 @Gajotres 编写了最佳解决方案(!)。



Using only jQuery and basic Javascript.

仅使用 jQuery 和基本的 Javascript。

For both, "plug library" and "writing your own validation methods", first check if the direct use of jQuery is what you need.

对于“插件库”和“编写自己的验证方法”,首先检查直接使用jQuery是否是您所需要的。

Here a code that do all what the question say to need: validation on blur, keyup and "when submitting".

这里的代码可以完成问题所说的所有内容:对模糊、键盘输入和“提交时”的验证。

function validate(){
    var cnv = $('#countryName').val();
    if (!$.trim(cnv)) {
        alert('Country Name is required!');
        return false;
    } else { return true; }
}

$('#testForm').submit(validate);
$('#countryName').bind('blur keyup', validate);