Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make autocomplete field of material UI required?

I have tried a couple of ways in order to make the material UI's autocomplete field of type required but I am not getting the behavior that I wanted. I had encapsulated my field inside react hook form <Controller/> yet no luck. I want to trigger message 'Field is mandatory' on submit when nothing is added to the field.

Below is the code snippet, I have not removed comments so that it becomes a bit easier for others to understand the approach that I had followed earlier -

  <Controller
        name="displayName"
        as={
          <Autocomplete 
                  value={lists}
                  multiple
                  fullWidth
                  size="small"
                  limitTags={1}
                  id="multiple-limit-lists"
                  options={moduleList}
                  getOptionLabel={(option) => option.displayName}
                  renderInput={(params,props) => {
                   return (
                      <div>
                        <div className="container">
                          <TextValidator {...params} variant="outlined" label="Display Name*" className="Display Text" 
                            name="displayName"  id="outlined-multiline-static" 
                            placeholder="Enter Display-Name" size="small"
        onChange={handleDisplay}
         // validators={['required']} this and below line does throw a validation but the problem is this validation stays on the screen when user selects something in the autocomplete field which is wrong.
        // errorMessages={['This field is required']} 
        // withRequiredValidator
        
                            />
                        </div>
                      </div>
                    )
                  }}
                  />
        }
        // onChange={handleDisplay}
        control={control}
        rules={{ required: true }}
        // required
        // defaultValue={options[0]}
        />
        <ErrorMessage errors={errors} name="displayName" message="This is required" />

like image 944
Pushpendra Yadav Avatar asked Jun 29 '20 19:06

Pushpendra Yadav


2 Answers

You can use the following logic to get it worked. Though this might not be the best solution but works.

<Autocomplete 
    renderInput={(params) => (
        <TextField
            {...params}
            label={value.length === 0 ? title : title + " *"} //handle required mark(*) on label 
            required={value.length === 0}
        />
    )}
/>
like image 78
Nikhil Waykos Avatar answered Sep 16 '22 22:09

Nikhil Waykos


I tried using the built in required in textfield for autocomplete, and it works like a charm. Maybe you can use this as a reference.

<Autocomplete
    renderInput={(params) => {
        <TextField {...params} required />
    }
    // Other codes
/>
like image 21
stvin Avatar answered Sep 16 '22 22:09

stvin