manny
manny

Reputation: 415

How to validate RegExp with an if else statement in react?

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

Answers (3)

Ajith
Ajith

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

BadPiggie
BadPiggie

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

Code Maniac
Code Maniac

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

Related Questions