thclpr
thclpr

Reputation: 5938

Change color of input text field not working

I'm not sure what I could be doing wrong, but why when I test the regular expression /^[\d{9}]*$/ on the website https://regex101.com/#javascript it match correctly if it's a number or not, but when I apply the RegEx on the JavaScript it doesn't work properly? I mean, its only showing red for numeric or characters. Instead green for numeric and red for characters. HTML:

<input type="text" name="age" id="msisdn" onKeyUp="checkKey()"> 

JavaScript:

function checkKey() {
    var msisdn = document.getElementById("msisdn");

    if (msisdn.value == /^[\d{9}]*$/) {
        msisdn.style.color = "#00b300";
    } else {
        msisdn.style.color = "#ff0000";
    }
}

Code on fiddler

Upvotes: 1

Views: 257

Answers (1)

Tushar
Tushar

Reputation: 87233

if(msisdn.value == /^\d{9}$/) { will compare the input value(string) against RegExp Object which will always return false.

Use RegExp#test

if(/^\d{9}$/.test(msisdn.value)) {

Updated Fiddle

And here's the shortest equivalent code

msisdn.style.color = /^\d{9}$/.test(document.getElementById("msisdn").value)
    ? "#00b300"
    : "#f00";

Fiddle


JavaScript is not needed just to change the color of the text when it is not following the regex, HTML & CSS can be used. HTML5 pattern attribute can be used on the <input> and :valid and :invalid pseudo-selectors can be used in the CSS.

input:invalid {
  color: #f00;
}
input:valid {
  color: #00b300;
}
<input type="text" id="msisdn" name="plaintext" pattern="\d{9}">

Upvotes: 5

Related Questions