I am trying to show error message if user enters something else in the input box which is not expected. The expected string is "games.yahoo.com" for example if "http://games.yahoo.com/game/ultimate-chess-flash.html" is passed it will return True. Below is my code but it is not working. The problem part is "else if (inThere==false)". Any kind of help is appreciated. Thank you. <script type="text/javascript"> function validateForm() { var gname = document.forms["myForm"]["gname"]; var inThere = gname.match(/games.yahoo.com/g); if (gname.value==null || gname.value=="") { alert("Can not be blank"); gname.focus() return false; } else if (inThere==false) { alert("Enter Correct URL"); gname.focus() return false; } else { var elem = document.getElementById('submit'); elem.style.display = 'none'; var elem = document.getElementById('myP'); elem.style.display = ''; } } </script> <form name="myForm" onsubmit="return validateForm();" method="POST" action="test.php"> <label>Enter Game URL: </label> <input name="gname" type="text" size="30" /> <button class="default blue" type="submit" id="submit"><span>Continue</span></button> </form>
Try replacing match with indexOf method. indexOf returns the position of the string in the other string. If not found, it will return -1. function validateForm() { var gname = document.forms["myForm"]["gname"]; var inThere = gname.indexOf("games.yahoo.com") if (gname.value==null || gname.value=="") { alert("Can not be blank"); gname.focus() return false; } else if (inThere == -1) { alert("Enter Correct URL"); gname.focus() return false; } else { var elem = document.getElementById('submit'); elem.style.display = 'none'; var elem = document.getElementById('myP'); elem.style.display = ''; } } Code (markup):