使用 jquery 验证名称字段

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

Validating name field using jquery

jqueryformsvalidation

提问by Sam

Actually I am new to jquery as well as web designing

实际上我是 jquery 和网页设计的新手

Now I need some piece of code which will invoke after blur event on a text box.

现在我需要一些将在文本框上的模糊事件之后调用的代码。

I need jquery code for validating a name field in the html form.

我需要 jquery 代码来验证 html 表单中的名称字段。

回答by Zoltan Toth

Try this - http://jsfiddle.net/gZNkt/

试试这个 - http://jsfiddle.net/gZNkt/

$("#fname").on("blur", function() {
    if ( $(this).val().match('^[a-zA-Z]{3,16}$') ) {
        alert( "Valid name" );
    } else {
        alert("That's not a name");
    }
});

It will check your name to be 3-16 characters long and contain only letters, so samwill validate, but 3sam- won't

它将检查您的姓名是否为 3-16 个字符长且仅包含字母,因此sam会进行验证,但是3sam- 不会

回答by Vins

Make sure you add a latest version of jQuery.... Here is a sample for validating for not null.

确保您添加了最新版本的 jQuery...。这是一个验证非空的示例。

    $(document).ready(function() {
        $('input#fname').on('blur', function() {
            if( $(this).val() == ''  || $(this).val() == "null") {
                // Your code to handle error
            } else {
                            return true;
                    }
        })
    });

回答by Durgaprasad Budhwani

I think you want to validate your text box after focus out or blur in jQuery.

我认为您想在 jQuery 中聚焦或模糊后验证您的文本框。

You can use below code for the same purpose :-

您可以将以下代码用于相同目的:-

$(document).ready(function()
{
   $("#fnam").blur(function() {

      if($(this).val() == null || $(this).val() == undefined || $(this).val() == "")
      {
         alert("field is empty");
      }

   });

// if you want this validation on focus lost
 $("#fnam").focusout(function() {

  if($(this).val() == null || $(this).val() == undefined || $(this).val() == "")
  {
     alert("field is empty");
  }

   });

});

回答by areeb

    $("#reg").bind("keypress", function (event) {
            if (event.charCode!=0) {
                var regex = new RegExp("^[a-zA-Z]+$");
                var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                if (!regex.test(key)) {
                    event.preventDefault();
                    return false;
                }
            }
        });

you disable press key and allow only charecters ....

回答by Isaac Gonzalez

Why dont you try with the jQuery Validate plugin

为什么不尝试使用jQuery Validate 插件