Two methods of judging whether the user input is a positive integer of by JavaScript


In project development, you need to use JavaScript to verify whether the user input is a positive integer.

Method 1:

var type="^[0-9]*[1-9][0-9]*$";
var r=new RegExp(type);
var flag=r.test(subjectHour.value);
if(!flag){
    alert(" Class hours should be a positive integer ");
    subjectHour.focus();
    return false;
}

Method 2:

var type="^[0-9]*[1-9][0-9]*$";
var re = new RegExp(type);
if(subjectHour.value.match(re)==null) {
    alert(" Please enter an integer greater than zero !");
    return false;
}

In fact, the two methods have the same idea, and both use regular expressions.

Above is this site to introduce you to use JavaScript to judge whether the user input is a positive integer (two methods), I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!