marcinb1986
marcinb1986

Reputation: 892

How to disable possibility to type numbers in string input field

I have input field from which is InputText from PrimeReact and content of this field should always be text, not figures. I want to disable possibility to type figures. Below is code example. I also tried to make validation if typeof data is 'number' and then display comment, but data from input as I see is always a string

 <FloatingLabel text="Name" name={`luxmeds.${index}.persons.${idx}.name`}>
                          <StyledInputText
                            name={`luxmeds.${index}.persons.${idx}.name`}
                            value={person.name}
                            onChange={handleChange}
                            type="text"
                          />
                        </FloatingLabel>
                        {!values.luxmeds[index].persons[idx].name && (
                          <StyledWarningText>{'You need to provide a name'}</StyledWarningText>
                        )}
                        {typeof values.luxmeds[index].persons[idx].name === 'number' && (
                          <StyledWarningText>{'You need to provide a name'}</StyledWarningText>
                        )}

Can You please suggest how to achieve that ?

regards

Upvotes: 0

Views: 145

Answers (1)

adsy
adsy

Reputation: 11437

You could just detect if the value passed to onChange contains a number, and if it does, do not set the state of person.name.

For example,

 const handleChange = (e) => {
      const numberRegex = /[0-9]/;
      if (!numberRegex.test(e.target.value)) {
        // set state
      }
   }

You might also consider using HTML5 pattern attribute:

                          <StyledInputText
                            name={`luxmeds.${index}.persons.${idx}.name`}
                            value={person.name}
                            onChange={handleChange}
                            type="text"
                            pattern="[a-zA-Z]*"
                          />

Upvotes: 2

Related Questions