最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to validate RegExp with an if else statement in react? - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Nov 15, 2019 at 7:02 Wang Liang 4,4447 gold badges25 silver badges50 bronze badges asked Nov 15, 2019 at 5:29 mannymanny 41511 silver badges24 bronze badges 2
  • Try if( new RegExp(/[^a-zA-Z\s]/).test(this.state.texts) ) – User863 Commented Nov 15, 2019 at 5:32
  • Or /[^a-zA-Z\s]/.test(this.state.texts) – ggorlen Commented Nov 15, 2019 at 5:32
Add a ment  | 

3 Answers 3

Reset to default 6

Instead of paring 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")
   }
}

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

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
  }


}
发布评论

评论列表(0)

  1. 暂无评论