I am new to react and created a login form with a few set of validations to raise errors in case of blank username or password. On the very first instance, when nothing is inserted and the Submit is clicked, it works fine. But once the value is changed with a value inserted by the user and then deleting from the text input, the variable gets a value of "" and never gets back to null value. This avoids my special treatment where I inserted !this.state.username. It gets stuck at that moment and the form submission goes anyway to the server. I have tried trim as well but it didn't work
class LoginClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
username: this.props.username,
password: this.props.password,
errorUsername: null,
errorPassword: null,
};
this.handleValidation = this.handleValidation.bind(this);
this.handleChange = this.handleChange.bind(this);
}
//assign textbox values to props
handleChange = (e) => {
this.setState({
[e.target.name]: [e.target.value],
});
};
//handle input validation
handleValidation = (event) => {
if (!this.state.username) {
this.setState({ errorUsername: "Please enter User Name" });
event.preventDefault();
}
if (!this.state.password) {
this.setState({ errorPassword: "Please enter Password" });
event.preventDefault();
}