I have made a react form, for usernames and passwords, and have a regex form to validate them.
I have a set state, to first set the value, then I pass in a callback to setState to then verify that the username is correct.
onChange={(e) => this.setState({username: e.target.value}, this.usernameValidator(this.state.username))}
I use the setState callback because I know it will be called each time something is changed, I'm not sure if I should call the method separately?
here is my handler
usernameValidator = (username) =>{
var usernameRegex = /^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$/;
if(usernameRegex.test(username)){
this.setState({
isUsernameCorrect: true
})
}else{
this.setState({
isUsernameCorrect: false
})
}
console.log(this.state.isUsernameCorrect)
}
my issue is that, whenever a user types for example 5 characters, which is passable to the regex pattern, and then deletes any number of characters, to an unacceptable number, the regex pattern will still pass.
How come this is happening, I mean onChange, should also check for deletions, and then the handler would validate again?
EDIT:
after comments, saying It's the regex pattern that is the problem i tried, using some console logs, to find the value of the current state, when It's validated
usernameValidator = (username) =>{
var usernameRegex = /^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$/;
if(usernameRegex.test(username)){
this.setState({
isUsernameCorrect: true
}, console.log('correct'))
}else if(!usernameRegex.test(username)){
this.setState({
isUsernameCorrect: false
}, console.log('not correct'))
}
console.log(this.state.isUsernameCorrect)
console.log(username)
}
it always logs, the username, before the next key is typed so for example if the given username is DDD
the passed in value will be DD because it gives in the username before the value is changed
onChangecode is incorrect. Look at the sandbox that @lux posted to see how to correctly write it.