0

目前,如果输入为空,我有一段 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;
                }


                        }`
4

1 回答 1

1

You need to use the pattern as below.

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')
}

You can simplify this but the example above has enough for you to be able to add the functionality you need.

Add your example to jsfiddle and if you have any problems, people can help you easier.

于 2014-05-07T15:17:21.693 回答