Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TextField] type='number' formatting #36415

Closed
VishnuCabot opened this issue Mar 3, 2023 · 4 comments
Closed

[TextField] type='number' formatting #36415

VishnuCabot opened this issue Mar 3, 2023 · 4 comments
Assignees
Labels
component: text field This is the name of the generic UI component, not the React module! support: Stack Overflow Please ask the community on Stack Overflow

Comments

@VishnuCabot
Copy link

VishnuCabot commented Mar 3, 2023

I have an Material UI TextField of type 'number'. That field should take only positive integers (when on typing and on pasting values to the field) and should not display scroll or should not respond to mouse wheel scroll or keyboard arrows. how should I do this ? ( scroll icons can be removed with CSS anyway )
Any help would be very much appreciated. Thank You!
scroll
neg
-ve
+

@mj12albert mj12albert self-assigned this Mar 3, 2023
@mj12albert mj12albert added the component: text field This is the name of the generic UI component, not the React module! label Mar 3, 2023
@mj12albert
Copy link
Member

mj12albert commented Mar 3, 2023

Thanks for reporting this ~ @VishnuCabot

These are common issues when using the HTML <input type="number"> (which is what the material TextField ultimately renders), and we advise against using it here: https://mui.com/material-ui/react-text-field/#type-quot-number-quot.

I think the simple workaround mentioned in the docs involving the HTML pattern attribute doesn't work as expected.

If you are trying to restrict to positive integers only, maybe you could try adding that check in your onChange handler, e.g.

const handleChange = (event) => {
  if (event.target.value.match(/[^0-9]/)) {
    event.preventDefault();
  }

  // otherwise, continue with the rest of your logic
  // ...
}

...

<TextField
  id="phone_number"
  label="Phone Number"
  variant="outlined"
  inputProps={{ inputMode: 'numeric' }}
  onChange={handleChange}
/>

We're also working on a proper number input component: #19154

@mj12albert mj12albert added the support: question Community support but can be turned into an improvement label Mar 3, 2023
@oliviertassinari oliviertassinari changed the title MUI TEXTFIELD type='number' formatting. [TextField] type='number' formatting Mar 3, 2023
@VishnuCabot
Copy link
Author

VishnuCabot commented Mar 5, 2023

Hi @mj12albert ,
Thanks for responding🙂
This is very crucial for me like I have to

  • restrict only numbers within that particular [Textfield] type='number' and have to

  • format the input to { xxx-xxx-xxxx } while on typing so as to improve the "User Experience".

You know, as a developer, you should be looking for every possible solutions out there, right 😬😀?!
I have been using a <Controller /> to wrap and control the Textfield and using YUP resolver to validate the field.

I tried many ways without trying out any external libraries and was checking whether I could do anything with the type="number" field.

It would be very much helpful if anyone could answer my query with a helping solution.

Attaching the solution I have implemented to get through the same scenario I have described.

The particular code is for ZIP input which is a 5 digit number of format { xxxxx } and will not accept 0 as first digit.

This works best for ZIP but I'm facing issues with PHONE NUMBER ( format - { xxx-xxx-xxxx } ) Input and there requires some good solution.

  • The change event handler :

const restrictInputOnlyNumbers = (val:string) => { if(val === "") return true if(val.length === 6) return false return rgxZIP.test(val) }

  • The rgxZIP :

const rgxZIP= /^[1-9][0-9]*$/;

  • The TSX :

           ```
    

<Controller
name="zip"
defaultValue=""
control={control}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<TextField
label={t('organization.zip')}
value={value}
onChange={(event) => {

                  const checkInput = restrictInputOnlyNumbers(event.target.value) 
                  event.target.value = event.target.value.slice(0,5) // required if backspace is pressed
                  return checkInput && onChange(event)

                }}

                onPaste={(event) => {
                  
                  const checkInput = restrictInputOnlyNumbers(event.clipboardData.getData('text')) 
                  return checkInput && onChange(event)

                }}
                id="zip"
                name="zip"
                variant="outlined"
                error={!!error}
                fullWidth
                margin="normal"
                helperText={error ? error.message : null}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '& fieldset': { borderColor: 'secondary.main' },
                  }
                }}
              />
            )}
          />
              

- The YUP schema (this won't be needed right ?!😬) :
` ,
    zip: yup
      .string().trim()
      .required(t('organization.required'))
      .matches(rgxZipCode,t('organization.invalidZIP'))
    ,`


Hoping the Best and Thank You !🙂🙂🙂

@mj12albert mj12albert added support: Stack Overflow Please ask the community on Stack Overflow and removed support: question Community support but can be turned into an improvement labels Mar 8, 2023
@github-actions
Copy link

github-actions bot commented Mar 8, 2023

👋 Thanks for using MUI Core!

We use GitHub issues exclusively as a bug and feature requests tracker, however,
this issue appears to be a support request.

For support, please check out https://mui.com/getting-started/support/. Thanks!

If you have a question on Stack Overflow, you are welcome to link to it here, it might help others.
If your issue is subsequently confirmed as a bug, and the report follows the issue template, it can be reopened.

@github-actions github-actions bot closed this as completed Mar 8, 2023
@mj12albert
Copy link
Member

@VishnuCabot Have a look at this sandbox to see how to restrict the input to numbers only: https://codesandbox.io/s/https-github-com-mui-material-ui-issues-36415-orxx4r?file=/src/App.tsx

We do not recommend using using type="number" for your use-case.

For formatting/masking the display to (000) 000-0000 you can refer to the demos here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: text field This is the name of the generic UI component, not the React module! support: Stack Overflow Please ask the community on Stack Overflow
Projects
None yet
Development

No branches or pull requests

2 participants