Skip to content

Commit

Permalink
Effectively Empty form validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Bhavatu committed Oct 18, 2024
1 parent 7f6493d commit 3e046a4
Show file tree
Hide file tree
Showing 2 changed files with 215 additions and 178 deletions.
38 changes: 37 additions & 1 deletion components/common/FeedbackForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,12 @@ const FeedbackForm = ({

const t = useTranslations();
const [sent, setSent] = useState(false);
const onDismiss = () => setSent(false);
const [formEmptyError, setFormEmptyError] = useState(false);
const onDismiss = () => {
setSent(false);
setFormEmptyError(false);
};

const pathname = usePathname();
const searchParams = useSearchParams();

Expand All @@ -70,6 +75,26 @@ const FeedbackForm = ({
const onSubmit = (formData) => {
const { name, email, comment, ...additionalResponse } = formData;

const isCommentEmpty = !comment || comment.trim() === '';
const areAllAdditionalFieldsEmpty = Object.values(additionalResponse).every(
(value) => {
if (Array.isArray(value)) {
return value.length === 0;
}
return value === '' || value === null || value === undefined;
}
);

const isFormEffectivelyEmpty =
feedbackSetting !== 'required' &&
isCommentEmpty &&
areAllAdditionalFieldsEmpty;

if (isFormEffectivelyEmpty) {
setFormEmptyError(true);
return;
}

const data = {
name,
email: emailSetting !== 'excluded' ? email : undefined,
Expand All @@ -85,6 +110,7 @@ const FeedbackForm = ({
),
};
setSent(true);
setFormEmptyError(false);
createUserFeedback({ variables: { input: data } });
};
const renderAdditionalField = (field) => {
Expand Down Expand Up @@ -292,6 +318,16 @@ const FeedbackForm = ({
<p>{t('feedback-error-content')}</p>
</Alert>
)}
{formEmptyError && (
<Alert
color="danger"
className="mt-3"
isOpen={formEmptyError}
toggle={onDismiss}
>
{t('form-effectively-empty-error')}
</Alert>
)}
<Button type="submit" color="primary">
{!mutationLoading && t('send')}
{mutationLoading && (
Expand Down
Loading

0 comments on commit 3e046a4

Please sign in to comment.