Reputation: 603
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
Upvotes: 0
Views: 612
Reputation: 684
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>
</>
);
}
Upvotes: 1
Reputation: 1953
You can try this:
I have added the link to the code https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/input.js
Go to https://ikqdn.csb.app/input
in 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
Phn:<input error={disable} type="number" value={value} onChange={handleChange}/>
<button disabled={!disable}>click</button>
Both are in alternative state, i.e. if one becomes valid, then other becomes invalid.
Initially disabled
must be true
because input is empty and
I have taken initial value of input
as null
as an indicator of not clicked.
This is the condition of input
error
Input is clicked and the length != 10
value !== null && disable
Upvotes: 0