skeptic01 skeptic01 - 3 months ago 10
Javascript Question

Input Validation using Multiple Regex

I have a text field in which users can enter numerical field with numerical operators. Following is a set of examples for valid input

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


I've the following logic which works. I iterate through each
regex
on
keyup
. I wanna know is there more elegant and better way to do this?

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";

}
}

Answer

You can set RegExp as value of pattern attribute at <input> element, use css :invalid to style background property of element; toggle className at element at input, focus events if element .value.length === 0 or :not(:focus) at css, set background to unset !important, else remove className to apply only css :valid, :invalid styles

input:invalid {
  background: red;
}
input:valid {
  background: green;
}
input:not(:focus), .clear {
  background: unset !important;
}
<input pattern="^(|>=\d+$|<=\d+$|>\d+$|<\d+$|\d+$|<> \d+$|<> \d+ to \d+$|\d+ to \d+)$">

<script>
  var input = document.querySelector("input[pattern]")
  input.onfocus = input.oninput = function() {
    this.classList.toggle("clear", this.value.length === 0)
  }
</script>