views:

43

answers:

3

Hi all, I have a function which I use to limit form inputs to numbers only, or number and decimals depending on the field. Allowing decimals and numbers is easy enough, but I am trying to take it a step further and allow only one decimal, while also making sure that decimal is not the first character in the field. I have successfully allowed only one decimal, and I have also made it so a decimal will only be allowed if "0" is the first digit, but I cannot get it to allow a decimal when ANY number is the first digit for some reason. I could make it work if I made a massive if statement, but I am trying to avoid that. Any suggestions?

            // this allows only one decimal, and only if the first character of the field is a zero
            else if ((('.').indexOf(keychar) > -1) && field == document.form.start_pay && document.form.start_pay.value.indexOf('.') <= -1 && document.form.start_pay.value.charAt(0) == ('0')){
                return true;
            }
+1  A: 

Change it to:

        else if ((('.').indexOf(keychar) > -1) && field == document.form.start_pay && document.form.start_pay.value.indexOf('.') <= -1 && /[0-9]+/.test(document.form.start_pay.value.charAt(0))){
            return true;
        }
mway
if we're going to regexes anyway, why not just do `/^\d+(?:\.\d+)?$/.test(document.form.start_pay.value)`, and check the whole thing?
rampion
realized that and was just about to update. :)
mway
Awesome, the `test()` method is exactly what I was looking for! Thanks a bunch!
typoknig
@rampion, what is the difference between what you said and what he had posted at first? what did you mean by "check the whole thing"?
typoknig
@typoknig: Like Sean Vieira's answer. Why bother manually checking for a period, then checking for a digit, when you can check both at once.
rampion
Oh, Ok, I get it now. I just didn't understand the regex statement fully. I had to modify it a bit to get exactly what I wanted, but this got me on the right track.
typoknig
+2  A: 
/^((?:\d\.\d)|(?:\d+))$/.test(document.form.start_pay)

will cover all of your cases. (Should pass 1, 100, 0.7, 8.3 and any other permutations you can think of but disallow .3, 1.21 ... etc.)

Line by line:

/ #Begin regular expression
    ^ #Starting at the beginning of the string
    ( #For group #1
        (?: #Match
            \d\.\d #A number followed by a literal . (\.) followed by a number
        )
    | #Or
        (?: #Match
            \d+ #A number one or more times
        )
    ) #End group 1
    $ #Followed by the end of the string
/ #End regular expression
Sean Vieira
Really nice explanation! Do you use an automated tool for that or did you just write it out yourself?
Marcel Korpel
I typed it out myself -- though, now that you mention it, I should check and see what's out there :-D
Sean Vieira
A: 

Change :

document.form.start_pay.value.charAt(0) == ('0')

To :

!isNaN(document.form.start_pay.value.charAt(0))
Babiker