【问题标题】:How to validate RegExp with an if else statement in react?如何在反应中使用 if else 语句验证 RegExp?
【发布时间】:2020-03-11 05:49:49
【问题描述】:

如果用户在响应中输入一个符号到文本输入中,如何提醒用户? 我试过这个

textChange = () => {
   if (this.state.texts == new RegExp(/[^a-zA-Z\s]/) ) {
       alert("No symbols allowed")
   }
}

但注意当符号输入时会发出警报

【问题讨论】:

  • 试试if( new RegExp(/[^a-zA-Z\s]/).test(this.state.texts) )
  • /[^a-zA-Z\s]/.test(this.state.texts)

标签: javascript regex reactjs react-native


【解决方案1】:

你需要使用test方法,而不是比较字符串的相等性和正则表达式对象,它根据传递的字符串匹配模式返回一个布尔值

textChange = () => {
   if (/[^a-zA-Z\s]/.test(this.state.text) ) {
      alert("No symbols allowed")
   }
}

【讨论】:

    【解决方案2】:

    使用testmatch 方法,

    textChange = () => {
       if (/[^a-zA-Z\s]/.test(this.state.text) ) {
          alert("No symbols allowed")
       }
    }
    
    

    textChange = () => {
       if (this.state.text.match(/[^a-zA-Z\s]/) !== null) {
          alert("No symbols allowed")
       }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用javascript的文本方法使用正则表达式进行验证。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 2021-02-20
        • 1970-01-01
        • 2016-11-13
        • 1970-01-01
        • 2022-01-19
        相关资源
        最近更新 更多