Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
React validation using Material UI's TextField components

I have been researching this for an hour now, and doesnt seem like there is much examples on this on the internet. I am trying to validate the input fields so that all fields are filled, otherwise there will be an error. Amount of characters doesnt matter, just need to fill the inputs.

So here is my state object

constructor(props) {
    super(props);
    this.state = {
      firstName: '',
      lastName: '',
      ...,
    
    };
  }

And here are the material ui textfields

<TextField
                className={classes.formInput}
                name="firstName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                error={!firstName}
                helperText="Name is required"
                label="First Name"
                variant="standard" />
              <TextField
                className={classes.formInput}
                name="lastName"
                onChange={e => this.handleChange(e.target.value)}
                required
                id=""
                type="text"
                InputLabelProps={{
                  shrink: true,
                }}
                label="Last Name"
                variant="standard" />

And here is the onchange handler

   handleChange = (e) => {
     this.setState({
       [e.target.name]: e.target.value
     });
   }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Most likely that you want to add this validation only after user trying to submit the form. Then, you should create a new state for formError and add it to your submit function condition which will check that if your inputs are empty then set state of formError to true. After that, your expression for input error state will look like:

error={formError && firstName.length === 0}

You will get a nice user experience when your inputs will be highlighted with red only when there was an attempt to submit a form with empty inputs.

about 4 years ago · Juan Pablo Isaza Relatório

0

When the user is submitting the form, since all you want to do is validate that something is filled into the firstName and lastName fields, you can check this with either:

this.state.field !== '' //returns true if it's filled in

or

this.state.field.length > 0 //returns true if it's filled in

in whatever 'handleSubmit' function you create, you can call a seperate function to validate all your fields. That validating function can look like this:

// returns 'true' if fields filled out, and 'false' if not 
validateForm = () => {
  if (this.state.firstName === '' || this.state.lastName === '') {
    //set error message: 'Please fill out all fields')
    return false;
  } else {
    return true;
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda