user754443
user754443

Reputation: 47

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(/[-0-9]+/, "g");
if(!validationRegex.match(text.value)
{
 alert('Please enter only numbers.');
}

Upvotes: 3

Views: 9513

Answers (3)

Katie Kilian
Katie Kilian

Reputation: 6985

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

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227200

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/

Upvotes: 0

n00dle
n00dle

Reputation: 6043

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]/

Upvotes: 1

Related Questions