2

I use Material UI in my project and I would like to allow the user to choose between comma or period as decimal separator. They are not currency input fields, but just numerical fields that can have decimal places. Currently only period is accepted, if the user presses comma instead nothing happens.

3
  • you must have added the type of that input field to be 'number'. Thats why it is restricting you to add only 0-9 and '.' Commented Aug 11, 2020 at 8:34
  • What you can do here, to make it work with , or any special character to be treated as the decimal separator. You use a Regex that will test the value of the input field on every keystroke, to check if it has that particular special character use while maintaining the rules of a floating point number. Commented Aug 11, 2020 at 8:37
  • it is number type. and only period is accepted. and thanks for your suggestion, but first the number field has to accept comma and it does not Commented Aug 11, 2020 at 8:39

1 Answer 1

4

Making its type='number' will restrict the value parsing logic to the default one added in the html. if we want to parse the value entered in the field by our rules, we have to parse it explicitly. For that purpose we can use a regex to test the input value coming on on each keystroke on the field. and then will restrict populating the value if it restricts the rule.

You can use a following Regex to test for the input

//Dot: /^\d+(\.\d{0,2})?$/
//Comma: /^\d+(,\d{0,2})?$/

You see the running demo here: https://codesandbox.io/s/material-demo-forked-2gmmn?file=/demo.js

Sign up to request clarification or add additional context in comments.

2 Comments

I see. thanks for your example code. but what would do to switch between comma and period on the fly? if no separator was used yet, then the separator will be the one the user presses first, instead of selecting the separator from a dropdown menu
Simple, don't test the regex, until you get comma or period. Once you have that set, start testing on the relevant regex and you'll be fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.