Thales Pereira Thales Pereira - 2 months ago 10
HTML Question

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

on the website 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.

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


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

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

Code on fiddler


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 = /^\d{9}$/.test(document.getElementById("msisdn").value)
    ? "#00b300"
    : "#f00";


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