Skip to content

Commit

Permalink
Align disabled state with email validation
Browse files Browse the repository at this point in the history
Previously, the submit button of the "Add another email address"
form would be disabled if an email didn't match the pattern
"<something>@<something>.<something>". However, form submit was
left to be handled by client-side validation by the browser. Thus,
it was possible to submit the form with an email address that was
technically valid (e.g. "testtest@mailinator") even though the
submit button was still disabled. Thus, this change makes the
button's disabled state depending on the browser's form validation.

Note that I also added the check that some data was actually
entered - the browser doesn't report on invalid form fields until
the user has actually entered some data into that form. This is
good UX, but the button can provide feedback earlier.
  • Loading branch information
Vinnl committed Aug 21, 2024
1 parent e701af7 commit 46cb9a8
Showing 1 changed file with 11 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

"use client";

import { ChangeEvent, useEffect, useState } from "react";
import { ChangeEvent, useEffect, useRef, useState } from "react";
import { useFormState } from "react-dom";
import { useOverlayTriggerState } from "react-stately";
import { useOverlayTrigger } from "react-aria";
Expand Down Expand Up @@ -84,6 +84,7 @@ export const EmailAddressAdder = () => {
const EmailAddressAddForm = () => {
const l10n = useL10n();
const recordTelemetry = useTelemetry();
const formRef = useRef<HTMLFormElement>(null);
const [formState, formAction] = useFormState(onAddEmail, {});
const [hasPressedButton, setHasPressedButton] = useState(false);
const [email, setEmail] = useState("");
Expand All @@ -101,11 +102,7 @@ const EmailAddressAddForm = () => {
};

const isEmailValid = () => {
// Regex for checking email format
// ensuring it contains a local part, an "@" symbol,
// and a domain part.
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
return email.length > 0 && (formRef.current?.reportValidity() ?? false);
};

return !formState.success ? (
Expand All @@ -115,7 +112,11 @@ const EmailAddressAddForm = () => {
total: CONST_MAX_NUM_ADDRESSES,
})}
</p>
<form action={formAction} className={styles.newEmailAddressForm}>
<form
action={formAction}
ref={formRef}
className={styles.newEmailAddressForm}
>
<label htmlFor="newEmailAddress">
{l10n.getString("add-email-address-input-label")}
</label>
Expand All @@ -131,7 +132,9 @@ const EmailAddressAddForm = () => {
className={styles.btn}
disabled={!isEmailValid()}
onPress={() => {
setHasPressedButton(true);
if (isEmailValid()) {
setHasPressedButton(true);
}
}}
isLoading={hasPressedButton}
>
Expand Down

0 comments on commit 46cb9a8

Please sign in to comment.