[英]How to validate phone number in react that until user give valid phone number button should disabled
import React,{useState} from "react";
export default function Validate() {
const [value, setValue] = useState("");
const [disable, setDisable] = useState(false);
function handleChange(e) {
setValue(e.target.value);
if (e.target.value.length <10)
{
setDisable(true);
}
}
return (
<>
Phn:<input error={disable} type="number" value={value} onChange={handleChange}/>
<button disabled={!disable}>click</button>
</>
);
}
in this case initially button is disabled but when i type one number button is enabled but i need untill user give 10 digit phone number button is disabled在这种情况下,最初按钮被禁用,但是当我输入一个数字按钮时,我需要直到用户提供 10 位数的电话号码按钮被禁用
import React,{useEffect, useState} from "react";
export default function Validate() {
const [value, setValue] = useState("");
const [disable, setDisable] = useState(true);
function handleChange(e) {
setValue(e.target.value);
}
useEffect(() => {
setDisable(value.length !== 10);
}, [value])
return (
<>
Phn:<input error={disable} type="number" value={value} onChange={handleChange}/>
<button disabled={disable}>click</button>
</>
);
}
You can try this:你可以试试这个:
I have added the link to the code https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/input.js我已经添加了代码https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/input.js的链接
Go to https://ikqdn.csb.app/input
in codesandbox browser
Go 到https://ikqdn.csb.app/input
在代码和codesandbox browser
中输入
What you are missing in the code is您在代码中缺少的是
function handleChange(e) {
setValue(e.target.value);
if (e.target.value.length <10) <-- not updating the disable if length = 10
{
setDisable(true);
}
}
and in the input
and button
error and disable并在input
和button
错误和禁用
Phn:<input error={disable} type="number" value={value} onChange={handleChange}/>
<button disabled={!disable}>click</button>
Both are in alternative state, ie if one becomes valid, then other becomes invalid.两者都在替代 state 中,即如果一个变为有效,则另一个变为无效。
Initially disabled
must be true
because input is empty and最初disabled
必须为true
,因为输入为空并且
I have taken initial value of input
as null
as an indicator of not clicked.我将input
的初始值设为null
作为未点击的指标。
This is the condition of input
error Input is clicked and the length != 10这是input
错误的条件输入被点击并且长度!= 10
value !== null && disable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.