jurassix / react-validation-mixin

Simple validation mixin (HoC) for React.
MIT License
283 stars 38 forks source link

Preferred method of validating a checkbox? #31

Closed iamhaas closed 9 years ago

iamhaas commented 9 years ago

How would I go about validating whether a checkbox is on? The validation seems to be triggered when I click on the checkbox (turning it on) and when I turn it off validation goes away. When it is clicked on again nothing is triggered.

My JOI validatorTypes looks like this

validatorTypes:  {
    agree: Joi.any().valid('on').required().label('Agree Checkbox')
}

and my input looks like this

<input
  id="agreeCheckbox"
  type="checkbox" 
  name="agree" 
  className="formControl" 
  ref="agree"
  valueLink={this.linkState('agree')}
  onBlur={this.handleValidation('agree')}/>

Thanks in advance

jurassix commented 9 years ago

Try binding to the onChange event instead of the onBlur.

<input
  id="agreeCheckbox"
  type="checkbox" 
  name="agree" 
  className="formControl" 
  ref="agree"
  valueLink={this.linkState('agree')}
  onChange={this.handleValidation('agree')}/>
iamhaas commented 9 years ago

Putting that validation on the onChange doesn't allow me to actually click the checkbox i.e. when I click on it, it stays unchecked.

jurassix commented 9 years ago

Yeah that makes since because you are using the LinkStateMixin try the following instead:

<input
  id="agreeCheckbox"
  type="checkbox" 
  name="agree" 
  className="formControl" 
  ref="agree"
  value='on'
  checked={this.state.agree === 'on'}
  onChange={this.onCheckboxChange('agree')}/>

...
onCheckboxChange: function(fieldName) {
  return function (event) { 
    var value = event.target.value;
    var state = {};
    state[fieldName] = value;
    this.setState(state, this.handleValidation(fieldName));
  }.bind(this);
}
1django commented 9 years ago

That last suggestion works for me. Almost. When I click the checkbox, I see the following error in the console: Uncaught TypeError: Cannot read property 'preventDefault' of undefined. It all works though. Actually, I don't appear to be able to uncheck the box after I've checked it.

The error appear to be in the handleValidation() method here.

Also, can this same approach be used for radio inputs as well?

jurassix commented 9 years ago

I'll put together some examples for these scenario's over the weekend. stay tuned.

1django commented 9 years ago

Thanks...appreciated!

jurassix commented 9 years ago

checkbox radio