简体   繁体   中英

Validate input time (in minutes)

I need to put in a field the input of time in minutes so I create this regular expression in javascript:

var pattern = new RegExp('[1-9]+[0-9]*') //the 0 is not a correct value for input

var example = "44445/";
if (pattern.test(example)) {

}

My problem is that the program enters in the if also in the string there is the "/" value. How is it possible?Anyone can example me?

You missed the start and end anchors. If you don't use anchors, then the regular expression will only check if the string contains the numbers.

Using anchors will make sure that the string contain only the specified characters.

var regex = /^[1-9]+[0-9]*$/;

Your regex can also be written as

var regex = /^[1-9]\d*$/;

 function testValue(value) { return /^[1-9]\\d*$/.test(value); } 
 <input type="text" onblur="document.getElementById('i1').value = testValue(this.value)"> <input type="text" readonly id="i1"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM