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
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;" />
Alternative, you can try this
<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">
0
source to share