What's wrong with my regex in web input?

I would like to limit to a positive integer or 0. So I wrote this code:

<input type="text" name="age" id="age" value="${po.age}"  
     onkeyup="value=value.replace(/[^[1-9]\d*|0]/g,'')" 
     style="ime-mode:disabled;" onpaste="return false;"
    />

      

But I find that I can only enter 1-9. If I find 0, it will be removed. How to fix it?

+3


source to share


5 answers


You can just use type input number

and set the value min

to 0:



Try me:
  <input type="number" min="0">
      

Run codeHide result


+3


source


You can try this:

<input type="text" name="age" id="age" value="${po.age}" onkeyup="value = value.replace(/[a-z]|-/gi, ''); value = parseInt(value.match(/\d+|\./gi).join('')) || '';" style="ime-mode:disabled;" onpaste="return false;"
/>

      



https://jsfiddle.net/2vamj5w0/

+2


source


Simply you can write a regex like this if you want any digit followed by a zero

/ [1-9] \ d * [0] {1} /

+1


source


Just change the code value=value.replace(/[^[1-9]\d*|0]/g,'')

to value=value.replace(/[^[0-9]\d*/g,'')

so it will look like

<input type="text" name="age" id="age"  onkeyup="value=value.replace(/[^[0-9]\d*/g,'')" style="ime-mode:disabled;" onpaste="return false;" />
      

Run codeHide result


Alternative, you can try this

<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
      

Run codeHide result


0


source


Can you use something like this:

value=isNaN(parseInt(value,10))?"":parseInt(value,10)<0?"":parseInt(value,10)

      

0


source







All Articles