Reputation: 415
how to alert a user if the user types a symbol into a text input in react? I tried this
textChange = () => {
if (this.state.texts == new RegExp(/[^a-zA-Z\s]/) ) {
alert("No symbols allowed")
}
}
but noting is alerting when a symbol is type
Upvotes: 1
Views: 2980
Reputation: 2666
You can use text method of javascript to validate using regular expression.
textChange = () => {
const expression = /[^a-zA-Z\s]/;
var notValid = expression.test(String(this.state.texts));
// notValid will be true if entered text does'nt match the expression
if(notValid){
alert("No symbols allowed");
}else{
//Valid value
}
}
Upvotes: 2
Reputation: 6359
Use test
or match
methods,
textChange = () => {
if (/[^a-zA-Z\s]/.test(this.state.text) ) {
alert("No symbols allowed")
}
}
or
textChange = () => {
if (this.state.text.match(/[^a-zA-Z\s]/) !== null) {
alert("No symbols allowed")
}
}
Upvotes: 4
Reputation: 37755
Instead of comparing the equality of string with the regex object, you need to use test
method, which returns a boolean value based on the passed string matching pattern or not
textChange = () => {
if (/[^a-zA-Z\s]/.test(this.state.text) ) {
alert("No symbols allowed")
}
}
Upvotes: 6