简体   繁体   中英

How to validate a radio button in react.js?

I have a group of radio buttons that check for the user's gender.

this is my radio button mark up.

export default class Gender extends React.Component {
    genderRow(gender) {
        return (
            <Radio onBlur={this.props.validate} key={gender.id} name="gender" value={gender.id} label={gender.text} onChange={this.props.onChange}/>
        )
    }
    render() {
        let genderError;
        if(this.props.errors.gender) {
            genderError = <span className="has-error">Gender is required</span>
        } else {
            genderError = null;
        }
        return (
            <div>
                {genderError}
                {this.props.gender.map(g => this.genderRow(g))}
            </div>
        )
    }
}

onBlur I am trying to call the following function.

validate(event) {
        let name = event.target.name;
        let errors = this.state.errors;
        if(!event.target.value) {
            errors[name] = true;
            this.setState({ errors: errors })
        }
    }

The issue is as follows. Since the radio button is a controlled component, there is always a truthy value, which means that when I check for !event.target.value it will return false, and this is happening even if the user didn't actually choose a value.

In your onChange handler, have it set the checked state:

onChange: function() {
  this.setState({checked: !this.state.checked})
}

And then adjust your validation to:

validate(event) {
  let name = event.target.name;
  let errors = this.state.errors;
  if(!event.target.checked) {
    errors[name] = true;
    this.setState({ errors: errors })
  }
}

Actually React is a VIEW. So you should know that it does not have rich built in validation stuff like Angular have. If you have a lot of validation in plans or already you should look to some more advanced tools for this. Example - use Backbone models together with react react-backbone (just as a live example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM