js limits text boxes to integers or Numbers with decimal points

  • 2020-06-01 08:18:08
  • OfStack

When you do form validation, do you have to verify that an input field can only be filled with Numbers, only integer Numbers or Numbers with decimal points? The following code may help you! The form is fully validated by defining the onkeypress, onkeyup, and onblur events for the current input box, and the results are quite reliable.

<input type="text" value="" t_value="" o_value="" onkeypress="if(!this.value.match(/^[\+\-]?\d*?\.?\d*?$/))this.value=this.t_value;else this.t_value=this.value;if(this.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/))this.o_value=this.value" onkeyup="if(!this.value.match(/^[\+\-]?\d*?\.?\d*?$/))this.value=this.t_value;else this.t_value=this.value;if(this.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/))this.o_value=this.value" onblur="if(!this.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?|\.\d*?)?$/))this.value=this.o_value;else{if(this.value.match(/^\.\d+$/))this.value=0+this.value;if(this.value.match(/^\.$/))this.value=0;this.o_value=this.value}" />

The following is a brief explanation of the onkeypress, onkeyup and onblur incidents.

The onkeypress event occurs when a keyboard key is pressed and a key is released.

The onkeyup event occurs when the keyboard keys are released.

The onblur event occurs when an object loses focus.

In addition, it should be noted that if the form needs to be strictly verified, the client side and the server side must be double verified, which has been done for the client side. If you know a little bit of the program, can easily bypass this piece of validation code, if the server did not carry out validation, it is very easy to go wrong.

That's all for this article, I hope you enjoy it.

Related articles: