Set the pattern of a text field to only contain numbers from 1 to 3:
document.getElementById("myText").pattern = "[1-3]";
Click button to set a regular expression that the text field's value will be checked against.
<!DOCTYPE html> <html> <body> <form action="/action_page.php"> Zip code: <input type="text" id="myText" name="zip_code"> <input type="submit"> </form>//from w w w.j av a 2s . co m <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { document.getElementById("myText").pattern = "[1-3]"; document.getElementById("myText").title = "A number from 1 to 3"; document.getElementById("demo").innerHTML = "The text field can now only contain numbers from 1 to 3."; } </script> </body> </html>