Reputation: 659
I want to add email validation to the input field and based on that disable the add button if the email entered by user is wrong.
below you can see my code,
function Parent() {
const [email, setEmail] = useState('');
const onEmailChange = (event: any) => {
setEmail(event.target.value);
};
const isDisabled = email.length === 0;
return (
<Input
type="email"
value={email}
onChange={onEmailChange}
placeholder="Insert user email"
/>
<button disabled={isdisabled}>Add</button> //add button to be disabled when user input email is wrong
);
}
I want to make sure i have basic email validation for the input and be able to enter only numbers, ''.
Could someone help me with this? Thanks in advance.
EDIT:
image for the error unnecessary escape character
Upvotes: 1
Views: 1881
Reputation: 3231
You can use regex
in order to check if the input value is an email by using the onChange()
property.
import React from "react";
const regex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i;
export default function App() {
const [isDisabled, setDisibility] = React.useState(true);
const checkEmail = e => {
setDisibility(!regex.test(e.target.value));
}
return (
<div>
<input onChange={checkEmail} placeholder="email address" />
<button disabled={isDisabled}>add</button>
</div>
);
}
https://codesandbox.io/s/dry-sun-votmt?fontsize=14&hidenavigation=1&theme=dark
Upvotes: 0
Reputation: 442
There are multiple ways of doing this but I would advise keeping a track of the disabled state of the button in its own state which is initialized to true.
Now change the disabled state inside a useEffect which runs every time the email is changed and set it to true or false based on your validation.
import React from "react";
// Modify this function as per your needs
const validateEmail = email => typeof email === "string" && email.includes("@");
export default function App() {
const [email, setEmail] = React.useState("");
const [isDisabled, setIsDisabled] = React.useState(true);
const onEmailChange = event => {
setEmail(event.target.value);
};
React.useEffect(() => {
setIsDisabled(!validateEmail(email));
}, [email]);
return (
<>
<input
type="text"
value={email}
onChange={onEmailChange}
placeholder="Insert user email"
/>
<button disabled={isDisabled}>Add</button>
</>
);
}
Here is the working prototype in codesandbox
Upvotes: 1