Skip to content

Commit

Permalink
fix: validation of form
Browse files Browse the repository at this point in the history
  • Loading branch information
dakshsinghrathore committed Dec 14, 2023
1 parent a581ee1 commit a091390
Showing 1 changed file with 5 additions and 24 deletions.
29 changes: 5 additions & 24 deletions src/stories/Components/Form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,8 @@ export default function Form() {
register,
handleSubmit,
formState: { errors },
watch,
} = useForm();

// Use watch to track changes in form values
const name = watch("name");
const email = watch("email");
const phone = watch("phone");
const option = watch("option");

const [isNameValid, setIsNameValid] = React.useState(false);
const [isEmailValid, setIsEmailValid] = React.useState(false);
const [isPhoneValid, setIsPhoneValid] = React.useState(false);
const [isOptionValid, setIsOptionValid] = React.useState(false);

React.useEffect(() => {
setIsNameValid(name?.length <= 30);
setIsEmailValid(email && /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email));
setIsPhoneValid(phone?.length === 10);
setIsOptionValid( !!option);
}, [name, email, phone, option]);

const onSubmit = (data) => {
console.log(data);
};
Expand All @@ -54,7 +35,7 @@ export default function Form() {

<address className="mt-2 not-italic">
{" "}
Level 1, Phoenix Tech Tower Plot No: 14/46, Survey No.1, IDA
Level 1, Phoenix Tech Tower Plot No : 14/46, Survey No.1, IDA
Uppal, Hyderabad, Telangana 500039
</address>
</div>
Expand All @@ -73,7 +54,7 @@ export default function Form() {
id="name"
{...register("name", { maxLength: 30 })}
/>
{errors.name && <p className="text-red-600 text-sm">Name shouldn't be more than 30 characters.</p>}
{errors.name && <p className="text-sm text-red-500">Name should not be more than 30 characters.</p>}
</div>

<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
Expand All @@ -94,7 +75,7 @@ export default function Form() {
},
})}
/>
{errors.email && <p className="text-red-600 text-sm">{errors.email.message}</p>}
{errors.email && <p className="text-sm text-red-500">{errors.email.message}</p>}
</div>

<div>
Expand All @@ -114,7 +95,7 @@ export default function Form() {
},
})}
/>
{errors.phone && <p className="text-red-600 text-sm">{errors.phone.message}</p>}
{errors.phone && <p className="text-sm text-red-500">{errors.phone.message}</p>}
</div>
</div>

Expand Down Expand Up @@ -176,7 +157,7 @@ export default function Form() {
</label>
</div>
</div>
{errors.option && <p className="text-red-600 text-sm">Please select at least one option.</p>}
{errors.option && <p className="text-sm text-red-500">Please select at least one option.</p>}

<div>
<label className="sr-only" htmlFor="message">
Expand Down

0 comments on commit a091390

Please sign in to comment.