非空、数字和字母的 javascript 验证

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

javascript validation for non empty,number and alphabets

javascripthtml

提问by Coder17

I have a form that accepts name, phone no. Currently, I have done validation for non empty fields. I want to add validation for name (alphabets) and phone no.(numbers).

我有一个接受姓名、电话号码的表格。目前,我已经对非空字段进行了验证。我想为姓名(字母)和电话号码(数字)添加验证。

My current code is given below. On submitting the form, I will be calling validateform()function:

我当前的代码如下。在提交表单时,我将调用validateform()函数:

function validateform()
{
    var str= true;
    document.getElementById("name").innerHTML="";

    if(document.frm.name.value=="")
    {
        document.getElementById("name").innerHTML="Please enter Name";
        str=false;
    }

    return str;
}

The value entered for name should be only alphabets. If not, I want to show the message "enter only alphabets". How should I do it?

为 name 输入的值只能是字母。如果没有,我想显示消息“仅输入字母”。我该怎么做?

回答by Dherya

/*mobile number of 10 digits */

/*10位手机号码*/

 var digit=10; 

 var pattern=/[0-9]{digit}/;

   if(!pattern.match ( phoneno ) )
         alert("not a valid number");

回答by Dimitar Dimitrov

As noted in the comments, you can try something like this:

如评论中所述,您可以尝试以下操作:

var rule = /^[a-zA-Z]*$/;
if(rule.test(document.frm.name.value)) {
   // this contains only letters !
}

回答by Marius ?verg?rd

You could use regex to achive what you're trying to do.

您可以使用正则表达式来实现您想要做的事情。

    function validatePhonenumber(value) {
         var regexp = /^[0-9]+?$/;
         return regexp.test(value);
    }

    function validateAlphabet(value) {
         var regexp = /^[a-zA-Z ]*$/;
         return regexp.test(value);
    }

回答by Nufail

var alphaExp = /^[a-zA-Z]+$/;
if(!document.frm.name.match(alphaExp))
    {
        document.getElementById("name").innerHTML="Please enter only alphabets";
        str=false;
    }

var numExp = /^[0-9]+$/;
if(!document.frm.phone.match(numExp))
    {
        document.getElementById("phone").innerHTML="Please enter only numbers";
        str=false;
    }

With this you don't need to check for empty input. If you want to handle empty input separately, replace +with a *in the regexes.

有了这个,你不需要检查空输入。如果要单独处理空输入,请在正则表达式中替换+为 a *

回答by kamran

function alphanumeric(inputtxt)  
{   
  var letters = /^[0-9a-zA-Z]+$/;  
  if(inputtxt.value.match(letters))  
  {  
    alert('Your registration number have accepted : you can try another');  
    document.form1.text1.focus();  
    return true;  
  }  
  else  
  {  
    alert('Please input alphanumeric characters only');  
    return false;  
  }  
} 

See more here.

在此处查看更多信息