Only accept number from 1 to 9 Using JavaScript
Would like to know how to only accept number to be entered into inputbox from 1 to 9 and if entered for example 0 give alert message, sorry not a valid number.
please check my function that i have done so far, but not working.. thank you
<input name="number1" type="text" size="1" id="number1"onkeyup="doKeyUpValidation(this)/>
doKeyUpValidation(text){
var validationRegex = RegExp(/[-开发者_Python百科0-9]+/, "g");
if(!validationRegex.match(text.value)
{
alert('Please enter only numbers.');
}
You're missing a closing quote at the end of your onkeyup
attribute, and as David mentions, you need to change your regex string to /[1-9]/
You were pretty close. Try this:
function doKeyUpValidation(text) {
var validationRegex = RegExp(/[1-9]+/, "g"); // The regex was wrong
if( !validationRegex.match(text.value) )
{
alert('Please enter only numbers.');
}
} // this was missing before
Your HTML is slightly wrong, it should be:
<input name="number1" type="text" size="1" id="number1" onkeyup="doKeyUpValidation(this)"/>
You need a space between each attribute, and each attribute needs to be quoted.
Also, your JavaScript has a few errors. It should be:
function doKeyUpValidation(text) {
var validationRegex = /[1-9]/g;
if (!validationRegex.test(text.value)) {
alert('Please enter only numbers.');
}
}
You need the function keyword to make doKeyUpValidation
a function. Also, your regex was a little off.
Demo: http://jsfiddle.net/EqhSS/10/
精彩评论