Home > Software engineering >  Handling multiple items in a single MUI/React TextField
Handling multiple items in a single MUI/React TextField

Time:12-06

I'm new to JS, React and MUI, and I have a MUI TextField that should accept multiple values like

1*10 5*50 13*250 5*50 1*10

3*33.33 4*25 3*33.33

on a single line. The elements consist of a positive integers, asterisks and positive floating points/integers. What is the best way to approach this?

I have tried writing an onChange handler and a regex for pattern recognition.

const format = /[1-9] [0-9]*\*[0-9]*[\.]?[0-9]*/g

This should match all possible values with no leading zeros and possible decimals after the multiplication asterisk. The numbers are arbitrary.

I can't wrap my head around how to disable user input/remove everything that doesn't match this pattern on the fly, since onChange changes the TextField value as soon as I press on a button.

Is there a way to mask this?

Are there better ways to do such input formatting?

CodePudding user response:

If you want to match the whole string, going by the pattern you're trying to implement, I would do this

^(?:\d \*\d*(?:\.\d*)? ?)*$

Here is a working example https://regex101.com/r/o8rvWH/1

If you watch to get the matching pattern you can do this

(\d \*\d*(?:\.\d*)?)

Here is a working example https://regex101.com/r/OtfWIp/1

CodePudding user response:

Here is my solution which includes most of your requisite. The leading zero is not left out, but ruled out with regexp.

(\b[1-9]\d*\*(?:0\.(?=\S [0-9])\d |[1-9]\d*(?:\.\d )?\b)(?= |$)) 

example: https://regex101.com/r/T9I7IV/1

I'm not familiar with javascript so you might need to change the \S.

  • Related