Skip to content

Commit 2311a7b

Browse files
committed
Update Hero.tsx
Fixed partial validation - It used to only check for empty input field... previously bunch of spaces only input was not considered empty by `required` attribute. - Added a proper validation in `handleSubmit()`
1 parent 6f0d23f commit 2311a7b

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

components/Hero.tsx

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { FormEventHandler } from 'react';
1+
import { FormEventHandler, useState } from 'react';
22
import Link from 'next/link';
33

44
import languages from 'assets/languages.json';
@@ -10,11 +10,20 @@ import Button from './Button';
1010
const { main: mainLanguages, others: otherLanguages } = languages;
1111

1212
function Hero() {
13+
const [errorMessage, setErrorMessage] = useState<string | null>(null);
1314
const router = useRouter();
1415
const handleSubmit: FormEventHandler = e => {
1516
e.preventDefault();
1617
const formData = new FormData(e.target as HTMLFormElement);
17-
const search = formData.get('search');
18+
const search = (formData.get('search') as string).trim();
19+
// Check if the input is empty or contains only spaces
20+
if (search === '') {
21+
setErrorMessage('Empty search terms invalid!');
22+
return;
23+
} else {
24+
// Clear any previous error message & proceed to search
25+
setErrorMessage(null);
26+
}
1827
router.push(`/repos/${search}`);
1928
};
2029
return (
@@ -65,7 +74,6 @@ function Hero() {
6574
placeholder="Search for your language"
6675
className="input input-bordered w-full text-neutral-100 border-2023-bavarian-gold-2 focus:outline-2023-bavarian-gold-2 max-w-xs rounded-tr-none rounded-br-none bg-transparent"
6776
name="search"
68-
required
6977
/>
7078
<button
7179
type="submit"
@@ -75,6 +83,11 @@ function Hero() {
7583
</button>
7684
</div>
7785
</form>
86+
{errorMessage && (
87+
<div
88+
className="text-red-500 animate-pulse animate-duration-1000"
89+
>
90+
{errorMessage}</div>)}
7891
{/* <a href="https://github.com/max-programming/hacktoberfest-projects/">
7992
<button className="m-2 border-0 hover:bg-primary-2 hover:text-black btn btn-lg">
8093
Add another language

0 commit comments

Comments
 (0)