Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.');
}
like image 823
user754443 Avatar asked Jan 29 '26 07:01

user754443


2 Answers

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

like image 124
n00dle Avatar answered Jan 30 '26 22:01

n00dle


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
like image 35
Katie Kilian Avatar answered Jan 30 '26 20:01

Katie Kilian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!