You won't need to create a state for the disabled. You can simply validate using it on every render. The sample is given below. Whenever you update input, the component will retrigger and validation will be performed.
import { useState } from "react";
import "./styles.css";
const blackListed = /^s@gmail\.com$/;
const emailReg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
const isEmailValid = (email = "") => {
if (!email.length) return false;
if (!emailReg.test(email)){
return false
}
return !blackListed.test(email);
};
export default function App() {
const [mail, setEmail] = useState("");
const handleChange = ({ target: { value } }) => {
setEmail(value);
};
const isValidEmail = isEmailValid(mail);
return (
<div>
<input value={mail} onChange={handleChange} maxLength="20" />
<button disabled={!isValidEmail}> Submit </button>
</div>
);
}
If you want to clear email after a certain time. You can use useEffect with setTimeout and watch for change.
useEffect(() => {
const id = setTimeout(() => {
if (!isValidEmail && mail.length) {
alert("Your email is invalid");
setEmail("")
}
}, 1000)
return () => clearTimeout(id);
}, [isValidEmail])
Complete code:
import { useState, useEffect } from "react";
import "./styles.css";
const blackListed = /^s@gmail\.com$/;
const emailReg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
const isEmailValid = (email = "") => {
if (!email.length) return false;
if (!emailReg.test(email)) {
return false
}
return !blackListed.test(email);
};
export default function App() {
const [mail, setEmail] = useState("");
const handleChange = ({ target: { value } }) => {
setEmail(value);
};
const isValidEmail = isEmailValid(mail);
// Clear after some toat and message.
useEffect(() => {
const id = setTimeout(() => {
if (!isValidEmail && mail.length) {
alert("Your email is invalid");
setEmail("")
}
}, 1000)
return () => clearTimeout(id);
}, [isValidEmail])
return (
<div>
<input value={mail} onChange={handleChange} maxLength="20" />
<button disabled={!isValidEmail}> Submit </button>
</div>
);
}
Working code:
https://codesandbox.io/embed/nervous-cache-tm5yt?fontsize=14&hidenavigation=1&theme=dark