Page 1 of 1

Numeric and Decimal only Entries: can this code do that?

Posted: Tue Feb 17, 2015 3:02 pm
by simonmlewis

Code: Select all

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
This code works by allowing only a numeric value to be entered, but I need to be able to add something like 2.5 as well. So can it be adjusted so a . can be entered?

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Tue Feb 17, 2015 3:14 pm
by Celauran
This is restricting the actual key codes, which seems like a strange approach. On my keyboard, period is 110 and decimal (on the numpad) is 190 if you want to continue down that road.

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Tue Feb 17, 2015 3:21 pm
by simonmlewis
Sorry? If there is a simpler way of doing it - so I can enter only numeric and decimal point... ?

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Tue Feb 17, 2015 4:53 pm
by Christopher
Google "javascript verify if string is numeric" to get some ideas. You should verify the value after input anyway.

And, if you are going to check keypresses, then you may need to track whether the user type '.' twice. You need to only allow '.NN', 'NN.NN' and 'NN.' , not something like '.NN.NN.'

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Tue Feb 17, 2015 5:02 pm
by simonmlewis
Very good point. They are unlikely to do that. It's mainly so they don't enter 2.5", but only enter 2.5. So if that was the only real concern, how could i adjust my code so that it takes 0-9 and . ?

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Tue Feb 17, 2015 8:09 pm
by Celauran
The bigger point here is to validate the data they have entered rather than trying to restrict what they can enter. 222.555.22.5.25 is no more valid than 2.5"

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Wed Feb 18, 2015 2:17 am
by simonmlewis
Yes I know, but these people know what to enter. I just want to stop them entering ". They know to enter 2.5, or 7. But they could easily do 2.5".

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Wed Feb 18, 2015 2:57 am
by simonmlewis
How would i filter out a " in code after submission? So if they did 2.5", how would i check for it and remove?

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Wed Feb 18, 2015 4:47 am
by simonmlewis
Ignore me, it's easy:

Code: Select all

$depth = str_replace("\"", "", $depth);

Re: Numeric and Decimal only Entries: can this code do that?

Posted: Wed Feb 18, 2015 11:59 am
by Christopher
Or more thorough:

Code: Select all

$depth = preg_replace('/[^0-9\.]/', '', $depth);