if(msisdn.value == /^\d{9}$/) { will compare the input value(string) against RegExRegExp Object which will always return false.
Use RegExp#test
if(/^\d{9}$/.test(msisdn.value)) { And here's the shortest equivalent code
msisdn.style.color = /^\d{9}$/.test(document.getElementById("msisdn").value) ? "#00b300" : "#ff0000";"#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}">