Skip to content

Commit

Permalink
feat: added validation for links in advertisement (#1516)
Browse files Browse the repository at this point in the history
- Implemented validation for the `formState.link` field to ensure that it represents a valid URL.
- Proper The validation checks have been added to prevent users from submitting arbitrary or
  invalid strings when creating a new advertisement.
- Added tests for the modified code.
- Ensured no other functionality or tests fail after the changes.

Signed-off-by: Akhilender <[email protected]>
  • Loading branch information
akhilender-bongirwar authored Feb 11, 2024
1 parent 7b2efcd commit 85c5534
Show file tree
Hide file tree
Showing 11 changed files with 74 additions and 7 deletions.
2 changes: 2 additions & 0 deletions public/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -701,6 +701,8 @@
"archievedAds": "Completed Campaigns",
"pMessage": "Ads not present for this campaign.",
"delete": "Delete",
"validLink": "Link is valid",
"invalidLink": "Link is invalid",
"Rname": "Enter name of Advertisement",
"Rtype": "Select type of Advertisement",
"Rlink": "Provide a link for content to be displayed",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,8 @@
"archievedAds": "Campagnes terminées",
"pMessage": "Aucune publicité n'est présente pour cette campagne.",
"delete": "Supprimer",
"validLink": "Le lien est valide",
"invalidLink": "Le lien n'est pas valide",
"close": "Fermer",
"deleteAdvertisement": "Supprimer l'annonce",
"deleteAdvertisementMsg": "Voulez-vous supprimer cette annonce ?",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/hi.json
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,8 @@
"archievedAds": "संपन्न अभियान",
"pMessage": "इस अभियान के लिए कोई विज्ञापन नहीं हैं।",
"delete": "हटाएँ",
"validLink": "लिंक मान्य है",
"invalidLink": "लिंक अमान्य है",
"close": "बंद करें",
"deleteAdvertisement": "विज्ञापन हटाएं",
"deleteAdvertisementMsg": "क्या आप इस विज्ञापन को हटाना चाहते हैं?",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/sp.json
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,8 @@
"archievedAds": "Campañas completadas",
"pMessage": "No hay anuncios disponibles para esta campaña.",
"delete": "Eliminar",
"validLink": "El enlace es válido.",
"invalidLink": "El enlace no es válido.",
"close": "Cerrar",
"deleteAdvertisement": "Eliminar anuncio",
"deleteAdvertisementMsg": "¿Desea eliminar este anuncio?",
Expand Down
2 changes: 2 additions & 0 deletions public/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,8 @@
"archievedAds": "已完成的广告活动",
"pMessage": "此广告活动没有相关广告。",
"delete": "删除",
"validLink": "链接有效",
"invalidLink": "链接无效",
"close": "关闭",
"deleteAdvertisement": "删除广告",
"deleteAdvertisementMsg": "您是否要删除此广告?",
Expand Down
4 changes: 4 additions & 0 deletions src/components/Advertisements/Advertisements.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,10 +213,14 @@ describe('Testing Advertisement Component', () => {
screen.getByLabelText('Enter name of Advertisement'),
'Cookie Shop'
);
userEvent.click(
screen.getByLabelText('Provide a link for content to be displayed')
);
userEvent.type(
screen.getByLabelText('Provide a link for content to be displayed'),
'http://yourwebsite.com/photo'
);
userEvent.click(screen.getByLabelText('Select type of Advertisement'));
userEvent.selectOptions(
screen.getByLabelText('Select type of Advertisement'),
'POPUP'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,9 @@
background-color: #31bb6b;
color: white;
}

.link_check {
display: flex;
justify-content: center;
align-items: flex-start;
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ const { getItem } = useLocalStorage();
jest.mock('react-toastify', () => ({
toast: {
success: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
Expand Down Expand Up @@ -110,7 +111,7 @@ describe('Testing Advertisement Register Component', () => {
type="BANNER"
name="Advert1"
orgId="1"
link="google.com"
link="https://google.com"
/>
}
</I18nextProvider>
Expand All @@ -136,7 +137,7 @@ describe('Testing Advertisement Register Component', () => {
type="BANNER"
name="Advert1"
orgId="1"
link="google.com"
link="https://google.com"
formStatus="edit"
/>
}
Expand All @@ -163,7 +164,7 @@ describe('Testing Advertisement Register Component', () => {
type="BANNER"
name="Advert1"
orgId="1"
link="google.com"
link="https://google.com"
/>
}
</I18nextProvider>
Expand Down Expand Up @@ -195,7 +196,7 @@ describe('Testing Advertisement Register Component', () => {
type="BANNER"
name="Advert1"
orgId="1"
link="google.com"
link="https://google.com"
/>
}
</I18nextProvider>
Expand Down Expand Up @@ -275,8 +276,8 @@ describe('Testing Advertisement Register Component', () => {

fireEvent.click(getByText(translations.register));
await waitFor(() => {
expect(toast.error).toBeCalledWith(
'An error occured, could not create new advertisement'
expect(toast.warn).toBeCalledWith(
'Link is invalid. Please enter a valid link'
);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import { useTranslation } from 'react-i18next';
import { toast } from 'react-toastify';
import dayjs from 'dayjs';
import { ADVERTISEMENTS_GET } from 'GraphQl/Queries/Queries';
import { Check, Clear } from '@mui/icons-material';
import { isValidLink } from 'utils/linkValidator';

interface InterfaceAddOnRegisterProps {
id?: string; // OrgId
Expand Down Expand Up @@ -50,7 +52,7 @@ function advertisementRegister({
const { t } = useTranslation('translation', { keyPrefix: 'advertisement' });

const [show, setShow] = useState(false);

const [isInputFocused, setIsInputFocused] = useState(false);
const handleClose = (): void => setShow(false);
const handleShow = (): void => setShow(true);
const [create] = useMutation(ADD_ADVERTISEMENT_MUTATION);
Expand Down Expand Up @@ -93,6 +95,10 @@ function advertisementRegister({

const handleRegister = async (): Promise<void> => {
try {
if (!isValidLink(formState.link)) {
toast.warn('Link is invalid. Please enter a valid link');
return;
}
console.log('At handle register', formState);
if (formState.endDate < formState.startDate) {
toast.error('End date must be greater than or equal to start date');
Expand Down Expand Up @@ -240,6 +246,8 @@ function advertisementRegister({
placeholder={t('EXlink')}
autoComplete="off"
required
onFocus={(): void => setIsInputFocused(true)}
onBlur={(): void => setIsInputFocused(false)}
value={formState.link}
onChange={(e): void => {
setFormState({
Expand All @@ -248,6 +256,21 @@ function advertisementRegister({
});
}}
/>
<div className="styles.link_check">
{isInputFocused && (
<p className="pt-2">
{isValidLink(formState.link) ? (
<span className="form-text text-success">
<Check /> {t('validLink')}
</span>
) : (
<span className="form-text text-danger">
<Clear /> {t('invalidLink')}
</span>
)}
</p>
)}
</div>
</Form.Group>
<Form.Group className="mb-3" controlId="registerForm.Rtype">
<Form.Label>{t('Rtype')}</Form.Label>
Expand Down
15 changes: 15 additions & 0 deletions src/utils/linkValid.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { isValidLink } from './linkValidator';

describe('Testing link validator', () => {
it('returns true for a valid link', () => {
const validLink = 'https://www.example.com';
const result = isValidLink(validLink);
expect(result).toBe(true);
});

it('returns false for an invalid link', () => {
const invalidLink = 'not a valid link';
const result = isValidLink(invalidLink);
expect(result).toBe(false);
});
});
8 changes: 8 additions & 0 deletions src/utils/linkValidator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const isValidLink = (link: string): boolean => {
try {
new URL(link);
return true;
} catch (error) {
return false;
}
};

0 comments on commit 85c5534

Please sign in to comment.