我想停止输入非字母字符

时间:2014-05-07 15:07:30

标签: javascript validation alphabetical letters

目前我有一段javascript,如果输入为空,则停止提交表单,但我想让脚本也停止输入非字母字符。

这是脚本

`function checkFormWhole(){

        //var theForm = document.getElementById(id);
        var letters = /^[A-Za-z]+$/;
        var letnums = /^[A-Za-z0-9]+$/;
        var theForm = document.getElementById("bookingForm");


            if (theForm.customerType.value == ""){
                alert("Please choose a customer type");
                return false;

                        }
            else if (theForm.customerType.value == "nonCorp" && theForm.forename.value == "") {
                    alert("Please Enter A Forename");
                    return false;

            }
            else if (theForm.customerType.value == "nonCorp" && theForm.surname.value == "") {
                    alert("Please Enter A Surname");
                    return false;

            }
            else if (checked == 0) {
                    alert("Please Choose An Event To Book");
                    return false;

            }
            else if (theForm.customerType.value == "corp" && theForm.companyName.value == "") {
                    alert("Please Enter A Company Name");
                    return false;

            }

我想要验证--->

else if (theForm.customerType.value == "nonCorp" && theForm.forename.value != (letters)  /*|| theForm.customerType.surname.value.match != (letters)*/) {
                        alert("Please Enter A Forename Containing ONLY letters");
                        return false;
                }


                        }`

1 个答案:

答案 0 :(得分:1)

您需要使用以下模式。

var str = '123456';
var str2 = 'abcdEFG';
var patt = /[^a-zA-Z]/g;
// Contains non alphabet chars
if(patt.test(str) === true) {
    console.log('Your input includes invalid characters')
}

// Contains alphabet chars only
if(patt.test(str2) === false) {
    console.log('Your input includes valid characters')
}

您可以简化此操作,但上面的示例足以让您能够添加所需的功能。

将您的示例添加到jsfiddle,如果您遇到任何问题,人们可以帮助您更轻松。