繁体   English   中英

javascript正则表达式以验证数据类型

[英]javascript regular expression to validate data types

我正在尝试使用正则表达式来验证数据类型。 该示例是关于要求数字的数字问题和要求字符串的数字问题。

因此,我尝试构建if语句,以便如果第一个问题或第二个问题是关于“父亲”或“数字”的,而答案不是数字,则发出警报,依此类推。

还要有另一个if语句,该语句说明问题是否与诸如此类(要求字符串答案)有关,而答案不是字符串,请发出警报。

不管按键是数字还是字符串字符,它都为我提供了“任何类型的按键按下事件都必须输入数字”的功能,谢谢您的投入。

    function validateDataType(word) {
        firstSelection = document.getElementById('firstQ').value;
        secondSelection = document.getElementById('secondQ').value;
        try{
            if ((firstSelection=="number"|firstSelection=="father"|secondSelection=="number"|secondSelection=="father")&&(!/^(?=.*\d).$/.test(word)))
            throw "You must type in a number.";
            else if (!/^(?=.*[a-z])(?=.*[A-Z]).$/.test(word))
            throw "You must type in text.";

        }
        catch(inputError){
            window.alert(inputError);
            return false
        }
        finally {
            document.forms[0].firstA.value ='';
            document.forms[0].secondA.value = '';
        }
        document.open();
        document.write("You entered valid answers");
        document.close();
    }

您需要使用|| 代替| 在您的if条件中:

if ((firstSelection=="number"||firstSelection=="father"||secondSelection=="number"||secondSelection=="father")&&(!/^(?=.*\d).$/.test(word)))
  • | 用于按位或

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM