【问题标题】:I want to stop non-alphabetical characters been put into the input我想停止在输入中输入非字母字符
【发布时间】:2014-06-24 15:36:46
【问题描述】:

目前我有一段 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;
                }


                        }`

【问题讨论】:

    标签: javascript validation alphabetical letters


    【解决方案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,如果您有任何问题,人们可以更轻松地帮助您。

    【讨论】:

    • 有没有办法可以使用我创建的函数中已有的代码来完成这项工作。
    • 将 patt 变量添加到您的函数中,并将 theForm.forename.value != (letters) 替换为 patt.test(theForm.forename.value) === true
    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 2012-12-29
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多