Skip to content
This repository has been archived by the owner on May 4, 2020. It is now read-only.

Preferred method of validating a checkbox? #31

Closed
iamhaas opened this issue Aug 25, 2015 · 7 comments
Closed

Preferred method of validating a checkbox? #31

iamhaas opened this issue Aug 25, 2015 · 7 comments
Labels

Comments

@iamhaas
Copy link

iamhaas commented Aug 25, 2015

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
Copy link
Owner

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
Copy link
Author

iamhaas commented Aug 26, 2015

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
Copy link
Owner

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
Copy link

1django commented Aug 28, 2015

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
Copy link
Owner

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

@1django
Copy link

1django commented Aug 28, 2015

Thanks...appreciated!

@jurassix
Copy link
Owner

checkbox
radio

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

3 participants