2 ms·
In most cases when you are accepting a numeric value it is best to just strip anything that isn't 0-9 then run validation on just the digits. There are some exc
by kevincox 2y ago
In most cases when you are accepting a numeric value it is best to just strip anything that isn't 0-9 then run validation on just the digits. There are some exceptions like phone numbers which may need + prefixes and similar but you can adjust these rules.
What I have found to work well is when the user unfocuses the input field or on submit strip everything but expected values then validate. If you want you can format the value at this time too (and the formatting won't interfere with text input).
If you want to get really fancy you can strip and format as they type and be careful to keep the formatting "virtual" such that the user is only editing the raw digits but this is very tricky to get right on all platforms and support all expected native editing UX. But even in the best cases this can have bad edge cases. For example the user pastes some text but it happens to have multiple numbers in it, if you eagerly strip and format what is left for the user will be these two numbers mushed together with misplaced separators or similar. If you let them paste, remove the unintended stuff, then format on blur this just works and is understandable.