1

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

2
  • Try if( new RegExp(/[^a-zA-Z\s]/).test(this.state.texts) ) Commented Nov 15, 2019 at 5:32
  • Or /[^a-zA-Z\s]/.test(this.state.texts) Commented Nov 15, 2019 at 5:32

3 Answers 3

6

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")
   }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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")
   }
}

Comments

2

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
  }


}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.