I got a login form with 2 inputs, basic username/password. I'd like to validate both text values to disable or enable the "Login" button.
For some reason, my TextInput isn't detecting when it's really empty on the first try, unless I press backspace again and then my button will be disabled/enabled. There has to be related on the way I'm saving the states.
This is the code:
I got my states here as follows:
this.state = {
loading: false,
username: {
text: '',
valid: false
},
password: {
text: '',
valid: false
},
isLoginValid: false
};
Then the buttons are these:
<TextInput
style={styles.textInput}
onChangeText={ (text) => { this.validateInput(text, 'username')}}
onKeyPress={ this.checkValidation.bind(this) }
value={this.state.username.text}
autoCapitalize={'none'}
placeholder={'Username'}
underlineColorAndroid="transparent"
/>
<TextInput
secureTextEntry={true}
style={styles.textInput}
onChangeText={ (text) => { this.validateInput(text, 'password')}}
onKeyPress={ this.checkValidation.bind(this) }
value={this.state.password.text}
autoCapitalize={'none'}
placeholder={'Password'}
underlineColorAndroid="transparent"
/>
And finally, these are the 2 functions where I handle the state for the button, don't worry about the boolean to enable/disable the button, that works fine.
validateInput(text, fieldname) {
var stateObject = {
text: text,
valid: text.length > 0
}
this.setState({ [fieldname]: stateObject });
}
checkValidation() {
var isValid = this.state.username.valid && this.state.password.valid;
this.setState({isLoginValid: isValid});
}
Any idea on how can I achieve this?