Home > Enterprise >  How to display an error message when fields are empty - React
How to display an error message when fields are empty - React

Time:09-22

I have a basic form with several fields. Some of them are required. I would like to display an "error" message to say that the field cannot be empty BEFORE the user clicks on the validation button. Also I would like to check the validity of the email

   export default class UploadFiles extends Component {
  constructor(props) {
    super(props);
    this.selectFile = this.selectFile.bind(this);
    this.upload = this.upload.bind(this);
    this.handleChangeForm = this.handleChangeForm.bind(this);

    this.state = {
      selectedFiles: undefined,
      currentFile: undefined,
      progress: 0,
      message: "",
      isError: false,
      fileInfos: [],
      typeSource:"avicca",
      hiddenUpload: false,
      entreprise: "",
      nom: "",
      prenom: "",
      email: "",
      telephone: "",
      sujet: "",
      commentaire: "",
    };
  }

  handleChangeForm(event) {
    const value = event.target.value;
    this.setState({
      ...this.state,
      [event.target.name]: value
    });
    console.log([event.target.name]   ' : '    event.target.value)
  }
  
   return (
      <div className="mg20">

        <Typography variant="h4" style={{ marginBottom: '0.5em'}}>
                  Test d'éligibilité
            </Typography>

      <FormControl style ={{minWidth: 120, verticalAlign:'middle', width:"100%", marginLeft:"60%"}}>
        <TextField 
          id="entreprise"
          name="entreprise" 
          label="Nom entreprise"
          value={this.state.entreprise}
          onChange={this.handleChangeForm}
          variant="outlined" margin="normal" fullWidth size="small" required/>

        <TextField 
          id="nom"
          name="nom" 
          label="Votre nom" 
          value={this.state.nom}
          onChange={this.handleChangeForm}
          variant="outlined" margin="normal" fullWidth size="small" required/>

        <TextField 
          id="prenom"
          name="prenom" 
          label="Votre prénom" 
          value={this.state.prenom}
          onChange={this.handleChangeForm}
          variant="outlined" margin="normal" fullWidth size="small" required/>

        <TextField 
          id="email" 
          name="email" 
          type="email" 
          label="Votre adresse email" 
          value={this.state.email}
          onChange={this.handleChangeForm}
          variant="outlined" margin="normal" fullWidth size="small" required/>

        <TextField 
          id="telephone"
          name="telephone" 
          label="Votre téléphone"
          value={this.state.telephone}
          onChange={this.handleChangeForm}
          variant="outlined" margin="normal" fullWidth size="small" required/>

        <TextField 
          id="sujet"
          name="sujet" 
          label="Le sujet"
          value={this.state.sujet}
          variant="outlined" margin="normal" size="small" />

        <TextField 
          id="commentaire"
          name="commentaire"  
          label="Commentaire"
          value={this.state.commentaire}
          variant="outlined" margin="normal" size="small"
          type='string' multiline row={3} minRows={3} />


        <label id="lbl-upload"  htmlFor="btn-upload" style={{margin:15}}>
          <input
            id="btn-upload"
            name="btn-upload"
            style={{ display: 'none' }}
            type="file"
            onChange={this.selectFile} />
          <Button
            className="btn-choose"
            variant="outlined"
            component="span"
            style={{marginLeft: "42%"}} >
             Parcourir
          </Button>

        </label>

         <Button
                  className="btn-upload"
                  color="primary"
                  variant="contained"
                  component="span"
                  disabled={!selectedFiles && !this.state.hiddenUpload}
                  onClick={this.upload}>
                  Envoyer
        </Button>
      </FormControl>

I'm still new to React, I guess what I want is with an onChange and handleChange that will look if the value is null or not

Note: I used to make forms with useStates but this time it's a class

If you need more informations, ask me.

CodePudding user response:

Because you set dynamic keys in your state you could check first if something is existing and then work with it of how you want.

So as example, your first field is called entreprise and while you type in that field you will have a new state: this.state.entreprise with a target.value

So if you would want to have an error poping up once entreprise field is empty you could go with something like this:

!this.state.entreprise && <do something>

Now, since you mentioned that you usually work with functional components this would propably be worth mentioning that the idea of useState and setState is pretty much the same, what differs is the way how less confusing and easier this is done with functional components and that in class component state is always an object where as functional ones it can be really any type.

CodePudding user response:

function validateEmail(email) {
    const re = /^(([^<>()[\]\\.,;:\s@"] (\.[^<>()[\]\\.,;:\s@"] )*)|(". "))@((\ 
    [[0-9] 
    {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z] 
    {2,}))$/;
    return re.test(String(email).toLowerCase());
}

You can use this function to validate an email. It contains a regular expression which checks whether a string is an email or not.

Also, you can use ternary operator like this to throw an error.

!this.state.email ? Error Message : null

Thanks

  • Related