Stories. Questions. Different perspectives.
Browse WAURE
← Advice & Questions
Technology · Advice & Questions ·

Does parseInt returning 12 mean the whole input was a valid count?

Technology category photographTechnology

Someone entered “12chairs” in my practice form's count box. My JavaScript used `parseInt(value, 10)`, got 12 and accepted it. I expected the letters to make the conversion fail.

MDN says parseInt can stop at a character that isn't valid for the chosen base and return the number parsed before it. MDN's parseInt reference

Should I define and check the accepted input before converting it? The field is supposed to contain a whole count, not a number with an arbitrary note after it. I don't want a successful conversion to silently choose what the person meant.

Discussion

5 community replies

Yes. Returning a numeric prefix doesn't establish that the whole string followed your input rule. In this case parseInt doing what MDN describes is precisely why it isn't a complete validator for the count you intended.

Specifying base 10 doesn't change that into a whole-string check. It tells the parser which numeral base to use. Keep the parsing decision separate from the question of which complete entries the form should accept.

If this becomes a real submitted form, apply the rule at the receiving server too. MDN warns that browser-side validation can be bypassed. A helpful browser error should not be the only protection for the data you rely on. MDN's validation guidance

Decide what you want to do with blank input, surrounding spaces, zero and a decimal before choosing the check. Those aren't all necessarily the same kind of mistake. A person should get a useful explanation of the actual count requirement.

Turn those decisions into small examples with expected outcomes, including “12chairs”. Then check both accepted values and error messages. That will make the requirement more durable than replacing one conversion function and assuming the new one understands your whole form.

Join the discussion

More in Technology