Reputation: 179
I have an entry that I am using for 'email' and 'password' and I want to do a check for both. I am using 'yup'.
I configured like this: I tried this way but it doesn't work for both.
type forgotPasswordData = {
email_or_phone: string;
}
var phoneValidation= /^([\s\(\)\-]*\d[\s\(\)\-]*){8}$/
var emailValidation= /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
const forgotPasswordSchema = yup.object().shape({
email_or_phone: yup.string().matches(phoneValidation, '').matches(emailValidation, '')
});
export default function ForgotPasswordCard() {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm({
mode: "onBlur",
resolver: yupResolver(forgotPasswordSchema),
defaultValues: {
email_or_phone: '',
}
});
const handleforgotPassword: SubmitHandler<forgotPasswordData> = async (data) => {
await new Promise((resolver) => setTimeout(resolver, 2000));
console.log(data);
};
And I left the 'input' like this:
<Input
type='text'
placeholder='Email or mobile number'
error={errors.email_or_phone}
{...register("email_or_phone")}
/>
Upvotes: 1
Views: 4719
Reputation: 886
You can do this with a single RegEx.
Here is that functionality on which you get Success response if you enter correct email or phoneNumber which length should be 10.
import React,{useState} from 'react';
export function App(props) {
const [value,setValue]=useState("");
const onSubmit=()=>{
var mailFormat = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|([0-9]{10})+$/;
if (value == "") {
alert( " Please enter your Email or Phone Number ");
}
else if (!mailFormat.test(value)) {
alert( "EmailAddress/PhoneNumber is not valid. Please provide a valid Email Address or phone number");
return false;
}
else {
alert("Success");
}
}
return (
<div className='App'>
<h1>{value}</h1>
<input placeholder={"TypeHere"} value={value} onChange={(e)=>setValue(e.target.value)}/>
<button onClick={onSubmit}>Submit</button>
</div>
);
}
Upvotes: 3