【发布时间】:2020-05-12 23:26:10
【问题描述】:
我正在尝试使用 if/else 语句验证 React JS 组件中的电话号码输入。如果用户输入字母而不是数字,我想显示一条消息(“请检查电话号码”)。到目前为止,我能够创建一个函数来检查输入值是否仅为数字,但是如果用户输入字母,我无法弄清楚如何显示消息警报(如在 Bootstrap/reactstrap 中)。
我的代码是
import React, { useState } from "react";
import { Alert } from "reactstrap";
export default () => {
const [number, setNumber] = useState(" ");
const numberHandleChange = (e) => {
e.preventDefault();
const re = /^[0-9\b]+$/;
if (e.target.value === "" || re.test(e.target.value)) {
setNumber(e.target.value);
console.log(e.target.value);
} else {
alert("please check your phone number");
}
};
return(
<label htmlFor="phone">
<h5>Phone</h5>
<input
type="tel"
name="phone"
id="phone"
placeholder="+0 000 00 00"
onChange={numberHandleChange}
/>
</label>
)}
我尝试从 Bootstrap 和 Reactstrap 导入 Alert 以在 else 函数中使用,它不起作用。 警报没有出现,而且输入字段也可以打印字母。
非常感谢任何建议。
谢谢。
【问题讨论】:
标签: javascript reactjs validation react-hooks