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

时间:2013-09-06 06:04:36

标签: javascript html

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

我目前的代码如下。在提交表单时,我将调用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;
}

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

5 个答案:

答案 0 :(得分:2)

/ *手机号码为10位* /

Private Sub Workbook_Open()
    Dim SourceList(0) As Workbook
    Dim PathList() As String
    Dim n As Integer
    PathList = Split("\data\WeaponInfo.csv", ",")

    ThisWorkbook.Activate
    Application.ActiveWindow.Visible = False
    Application.ScreenUpdating = False

    For n = 0 To Ubound(PathList)
        Workbooks.Open Filename:=ThisWorkbook.Path & PathList(n)
        Set SourceList(n) = ActiveWorkbook
        ActiveWindow.Visible = False
    Next

    Application.ScreenUpdating = True
    Workbooks.Open Filename:=ThisWorkbook.Path & "\HeroForge Anew 3.5 v7.4.0.1.xlsm", UpdateLinks:=3
    ActiveWindow.Visible = True

    Application.DisplayAlerts = False
    For n = 0 To UBound(SourceList)
        SourceList(n).Close
    Next
    Application.DisplayAlerts = True
End Sub

答案 1 :(得分:1)

如评论中所述,您可以尝试这样的事情:

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

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:1)

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;
    }

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

答案 4 :(得分:1)

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;  
  }  
} 

查看更多here