简体   繁体   English

下面的输入验证代码有什么问题?

[英]What is wrong in the below code of input validation?

I have trying to validate an input text field, which should contain only characters.我试图验证一个输入文本字段,它应该只包含字符。 I am using test() here.我在这里使用 test() 。 Ideally it should return true when the field is given string like "rent" but in every case it is going for the false scenario.理想情况下,当字段被赋予像“rent”这样的字符串时,它应该返回 true,但在每种情况下,它都适用于 false 场景。 Can someone please suggest why it is happening.有人可以建议为什么会这样。 I have tried debugging and found out that the values are coming fine in if statement.我试过调试,发现 if 语句中的值很好。 Please help.请帮忙。

    const [text,setText] = useState(" ")
    const [amount,setAmount] = useState(0)
  
    const {addTransaction} = useContext(GlobalContext)
    console.log(text,amount)


   const onSubmit = e =>{
   e.preventDefault(); 
   var letters = /^[A-Za-z]+$/;
  
   if(letters.test(text)){
   const newTransantion = {
   id: Math.floor(Math.random() * 10000000),
   text:text,
   amount:+amount
   } 
   addTransaction(newTransantion)
  }
  else{
    alert('Please give the correct input')
  }
}

I think the regex test function is working properly.我认为正则表达式测试功能工作正常。
Here is a sample.这是一个示例。 I would insert some debug prints around the code.我会在代码周围插入一些调试打印。

 var text = ["hello", "world", "4rent", "Howdy", "Buy", " spaces oh ", "99Bb"]; // Validation regex var letters = /^[A-Za-z]+$/; // Test validate our array values // for (const element of text) if ( letters.test( element ) ) console.log( element + " - passed" ); else console.log( element + " - failed" ); console.log( "\\n\\n\\n" );

I am guessing, that in the onSubmit function , the state variable "text" is empty string all the time.我猜,在 onSubmit 函数中,状态变量“text”一直是空字符串。

Does the input text field (we do not see here) have an onChange attribute??输入文本字段(我们在这里没有看到)是否有 onChange 属性? which should be a function updating the "text" state after every stroke.这应该是在每次笔画后更新“文本”状态的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM