msqar
msqar

Reputation: 3020

TextInput not realizing is empty until 2 'backspace' is pressed

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?

Upvotes: 3

Views: 1403

Answers (1)

SomoKRoceS
SomoKRoceS

Reputation: 3043

Try using onChangeText instead of onKeyPress. onChangeText passes the changed text as an argument for the callback, onKeyPress returns an object with the key pressed, so the warning is because the property text of password and username in state holds an object instead of string.

EDIT About the second problem (with the backspaces), note that onKeyPress is called before onChange callbacks, so the validation is happening before you set the changed text, Try removing onKeyPress at all, and make the validation check inside validateInput before you setState. So you will call setState once with the final properties you want to set.

Upvotes: 1

Related Questions