Forum Moderators: coopster

Message Too Old, No Replies

Extracting numeric value from alphanumeric input

         

SeanF

11:57 am on Feb 20, 2021 (gmt 0)

5+ Year Member Top Contributors Of The Month



I have a form which asks the user to input dimensions of an object. In spite of the fact that the form instructs users to enter decimal feet only, users often enter "14 ft." or "14 feet" or "14 ft 6in" or...

The Javascript which calculates follow-on values uses parseFloat(); to extract values and the works OK.

The question I have is: Is there an equivalent function in PHP?

Thanks

NickMNS

5:05 pm on Feb 20, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



This should not be handled server side but instead should be dealt with form validation. Using parseFloat() doesn't solve the problem, it simply hides it. parseFloat(14ft6in) returns 14 not 14.5, now 14 will allow your code to execute but it will return a value that is wrong, maybe almost right (which IMO is worse) but not correct.

Instead you should implement form validation, in this case, change the type attribute to your form to type="number". Then you can also add a min and max and a step value. The details are explained here:
[developer.mozilla.org...]

I would recommend using two fields for this case, one for feet and another for inches. The reason, as you have stated:
In spite of the fact that the form instructs users to enter decimal feet only, users often enter "14 ft." or "14 feet" or "14 ft 6in" or...

you can't fight the user. The users are accustomed to entering feet and inches, decimal feet are wonky and require the user to do math ("blah who likes doing math!" [sarcasm], I like math, but not when filling in forms), seriously, asking a user to do simplest calculation is a big ask. The problem really is that even if you use form validation, with decimal feet you have no way of knowing if when a user enters 14.6 that users really meant 14.6 or 14' - 7.2" or 14' - 6". By splitting the input it simplifies the validation, feet are input type=number with a step=1, min=0, thus will always be a positive integer. And inches will be type=number step=0.1 or 0.01 whatever precision suits your needs and min=0 and max=11.99. Then either server or client side, divide the inches value by 12 and add to the feet, and whammo! you have the right value to use and a happy user with no math required (for the user).

SeanF

8:32 pm on Feb 20, 2021 (gmt 0)

5+ Year Member Top Contributors Of The Month



Thanks, good advice!