Accept only a number from 1 to 9 Using JavaScript

I would like to know how to accept only the number that should be entered in the input field from 1 to 9, and if it is entered, for example, 0, a warning message is displayed, sorry for the invalid number.

please check my function which i have done so far but not working .. thanks

<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.');
}
+3
source share
3 answers

There is onkeyupno final quote at the end of your attribute , and as David mentions, you need to change the regex string to/[1-9]/

+1
source

You were pretty close. Try the following:

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
+1
source

HTML , :

<input name="number1" type="text" size="1" id="number1" onkeyup="doKeyUpValidation(this)"/>

, .

, JavaScript . :

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 a doKeyUpValidationfunction. In addition, your regex has been turned off a bit.

Demo: http://jsfiddle.net/EqhSS/10/

0
source

All Articles