I'm attempting to created a form validation using react-bootstrap, and would like to avoid making a validation function for each input.
I have this input:
<Input 
  hasFeedback 
  type="text" 
  label="Username" 
  bsStyle={this.state.UsernameStyle} 
  onChange={this.handleChange.bind(this, 'Username')} 
  value={this.state.Username} 
  bsSize="large" 
  ref="inptUser" 
  placeholder="Enter Username"
/>
Plus, I have two function to handle the validation and updating of the state:
handleChange: function(name, e) {
  var state = {};
  state[name] = e.target.value;
  this.setState(state);
  var namestyle  = name + 'Style';
  this.setState(this.validationState(namestyle, e));
},
&
validationState: function(style, event) {
  var length = event.target.value.length;
  if (length > 4) this.setState({style: 'success'});
  else if (length > 2) this.setState({style: 'warning'});
  return {style};
}
At this point if I change style to Username I can get this solution to work for that specific input as well. I could make an if statement and depending on the string I get in style I can call the appropriate setState, but is their a better way to do this?
Thanks!
var yourVariable = "name";
this.state[yourVariable];
is equivelant to:
this.state.name;
if you want to use your variable in set state you can use this:
var value = "peter";
this.setState({[yourVariable]: value});
is equivelant to:
this.setState({name: value)};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With