使用多个正则表达式进行输入验证

时间:2016-09-02 05:32:15

标签: javascript jquery

我有一个文本字段,用户可以使用数字运算符输入数字字段。以下是有效输入的一组示例

1. > 3
2. >= 3
3. < 3
4. <= 3
5. <> 3 (NOT)
6. 3 to 5 (RANGE)
7. <> 3 to 5 (NOT RANGE)

我有以下逻辑可行。我遍历regex上的每个keyup。我想知道有更优雅,更好的方法吗?

function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;
    var arrRegex = new Array("^>=\\d+$", "^<=\\d+$", "^>\\d+$", "^<\\d+$", "^\\d+$", "^<> \\d+$", "^<> \\d+ to \\d+$", "^\\d+ to \\d+$");
    c = false;
    for (i = 0; i < arrRegex.length; i++) {
        var regex = new RegExp(arrRegex[i]);
        if (regex.test(x)) {
            c = true;
        }
    }
    if (c == true) {
        document.getElementById("numb").style.backgroundColor = "green";

    } else {
        document.getElementById("numb").style.backgroundColor = "red";

    }
}

2 个答案:

答案 0 :(得分:0)

您可以在正则表达式中使用或(<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span id='actual_verse' class='context'> Hello There! </span> <div id='cal1'>&nbsp;</div> <div id='cal2'>&nbsp;</div> <div id='tooltip'> <div id='blue_box' class='boxes' title='Blue'></div> <div id='green_box' class='boxes' title='Green'></div> <div id='orange_box' class='boxes' title='Orange'></div> <div id='purple_box' class='boxes' title='Purple'></div> <div id='red_box' class='boxes' title='Red'></div> </div> <br> <br>)将它们组合成一个:

|

答案 1 :(得分:0)

您可以将RegExp设置为pattern元素的<input>属性值,使用css :invalid来设置元素的background属性;在className处的元素处切换input,在focus处的.value.length === 0:not(:focus)处设置css个事件,将background设置为{{ 1}},否则删除unset !important仅适用className css:valid个样式

:invalid
input:invalid {
  background: red;
}
input:valid {
  background: green;
}
input:not(:focus), .clear {
  background: unset !important;
}