0

I want to make the checkbox field mandatory to select atleast 1 using react js.

Below is my code:

 renderCheckboxes() {    
    const { zones_to_render_to_render, filter } = this.state;
    console.log(zones_to_render_to_render, filter)
    return zones_to_render_to_render
        .filter(checkbox =>
            filter === 'ALL' ||
            filter === 'CHECKED' && checkbox.checked ||
            filter === 'UNCHECKED' && !checkbox.checked
        )
        .map((checkbox, index) =>
            // console.log(checkbox, index)
            <div key={index}>
                <label>
                    <input
                        type="checkbox"
                        checked={checkbox.checked}
                        onChange={this.toggleCheckbox.bind(index)}                            
                    />
                    {checkbox.zone_name}
                </label>
            </div>
        );
}

Any help would be appreciated...

karthik
  • 21
  • 1
  • 8
  • In case of React it is better idea to handle `required` and other validations inside the submitting component, not where you rendering inputs. Assuming you using ajax/axios somewhere in parent component - make validations for required field there. – krylov123 Aug 02 '20 at 13:12

2 Answers2

2

Please add a required property to the checkbox.

required="required"

And wrap the input boxes into a form element. Define an onSubmit handler to the form which can make an ajax call with the input filled data.

More references here

Reactjs - Form input validation

Vasanth Gopal
  • 1,215
  • 10
  • 11
0

You can use Required property it is used to set or return whether the input checkbox field should be checked or not before submitting the form. for more details check https://www.geeksforgeeks.org/html-dom-input-checkbox-required-property/

<form >  
  <input
     type="checkbox"
     checked={checkbox.checked}
     onChange={this.toggleCheckbox.bind(index)}
     required="required"                        
   />
</form >