文本框的 Jquery 空验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9662383/
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-27 11:07:04  来源:igfitidea点击:

Jquery Empty validation for text box

jqueryvalidation

提问by

I've a text box in a form,when a user submits the form,it should check whether the user has filled it,other validation would be have some min characters,he has to fill.

我在表单中有一个文本框,当用户提交表单时,它应该检查用户是否填写了它,其他验证将有一些最小字符,他必须填写。

here is my code,which is not validating

这是我的代码,未验证


$('.textboxid').bind("submit", function() {
  if($(this).val() == "") {
    jQuery.error('Fill this field');
    return false;
  }
});

采纳答案by Starx

Your code is not validating because, you are binding submitevent on a textbox. You should use forms to do that.

您的代码未验证,因为您submit在文本框上绑定事件。你应该使用表格来做到这一点。

Apart from sudhir's answer, which will work fine. To provide an alternative to it. You can use regex validations too.

除了 sudhir 的答案,这将正常工作。为其提供替代方案。您也可以使用正则表达式验证。

An Nice example, which adds errors messages after the textbox as well.

一个很好的例子,它也在文本框后面添加了错误消息。

$("#yourFormId").submit(function() {
    var inputVal= $("#yourTextBoxId").val();
    var characterReg = /^([a-zA-Z0-9]{1,})$/;
    if(!characterReg.test(inputVal)) {
        $("#yourTextBoxId").after('<span class="error">Maximum 8 characters.</span>');
    }
});

回答by Sudhir Bastakoti

Try:

尝试:


$("#yourFormId").submit(function() {
  var textVal = $("#yourTextBoxId").val();
  if(textVal == "") {
    alert('Fill this field');
    return false;
  }
});


回答by Avin Varghese

 $(function () {

             var textVal = $("#yourTextBoxId").val();
             if (textVal == "") {
                 $("#error").fadeIn(500).show();

             } });

add the div where the error message should appear.

添加应该出现错误消息的 div。

 <div id="error">Enter Value...</div>