Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure only valid numeric characters are entered into a textbox?

Is there any existing jQuery functionality that can test if characters entered into a textbox are either numeric, or valid in a number?

Such as

.00 or 0.00, but not 0.00.00 or 0a

What I'd like to do is catch any invalid characters before they appear in the textbox.

If it's not possible with jQuery, what's the best way to approach this?

I know with JavaScript I can test isNaN() and then return false, but that's going to start getting hairy when I have to account for all possible keystrokes.

like image 335
DaveDev Avatar asked Dec 17 '22 20:12

DaveDev


1 Answers

just use a regex match

$('#formelement').val().match(/[-+]?[0-9]*\.?[0-9]+/)

(excluding selector, everything else is plain javascript)

As noted in comments, since you need to do it for each character inserted you have to consider an empty decimal part valid (eg. /[-+]?[0-9]*\.?[0-9]*/)

Since people in comments forces me to be precise I can suggest you how to work out how to use this matching for your purpose (but so you don't let anything to the OP imagination :( )

You can split the regex in 3 regexs, one for the first part (eventual sign and whole part), one for the first part plus the dot symbol and one for the whole number.

You validation routine should accept the input while it's being written if it matches at least one of the threes regex just described and the validation done at the end should accept just when the last regex is matched (since you are submitting the value and you need it to be correct)

like image 146
Jack Avatar answered May 22 '23 22:05

Jack