Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/app/api/submit/route.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
// import { NextResponse } from 'next/server';

// export async function POST(req: Request) {
// try {
// const { name, email } = await req.json();

// if (!name || !email) {
// return NextResponse.json({ message: 'Name and Email are required' }, { status: 400 });
// }

// return NextResponse.json({ message: `Thank you, ${name}!` });
// } catch {
// return NextResponse.json({ message: 'Server error' }, { status: 500 });
// }
// }

import { NextResponse } from 'next/server';

export async function POST(req: Request) {
Expand All @@ -8,8 +24,8 @@ export async function POST(req: Request) {
return NextResponse.json({ message: 'Name and Email are required' }, { status: 400 });
}

return NextResponse.json({ message: `Thank you, ${name}!` });
return NextResponse.json({ message: `Hello ${name}, your form has been submitted successfully!` });
} catch {
return NextResponse.json({ message: 'Server error' }, { status: 500 });
return NextResponse.json({ message: 'Internal server error' }, { status: 500 });
}
}
126 changes: 109 additions & 17 deletions src/app/form/page.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,118 @@
// 'use client';

// import { useState } from 'react';

// export default function Form() {
// const [name, setName] = useState('');
// const [email, setEmail] = useState('');
// const [message, setMessage] = useState('');
// const [loading, setLoading] = useState(false);
// const [error, setError] = useState('');

// const handleSubmit = async (e: React.FormEvent) => {
// e.preventDefault();
// setLoading(true);
// setMessage('');
// setError('');

// try {
// const res = await fetch('/api/submit', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ name, email }),
// });

// if (!res.ok) throw new Error('Failed to submit');
// const data = await res.json();
// setMessage(data.message);
// } catch {
// setError('Submission failed. Please try again.');
// } finally {
// setLoading(false);
// }
// };

// const handleReset = () => {
// setName('');
// setEmail('');
// setMessage('');
// setError('');
// };

// return (
// <div>
// <h1>Form Page</h1>
// <form onSubmit={handleSubmit}>
// <input
// type="text"
// placeholder="Enter your name"
// value={name}
// onChange={(e) => setName(e.target.value)}
// />
// <input
// type="email"
// placeholder="Enter your email"
// value={email}
// onChange={(e) => setEmail(e.target.value)}
// />
// <button type="submit" disabled={loading}>
// {loading ? 'Submitting...' : 'Submit'}
// </button>
// <button type="button" onClick={handleReset}>Reset</button>
// </form>
// {message && <p style={{ color: 'green' }}>{message}</p>}
// {error && <p style={{ color: 'red' }}>{error}</p>}
// </div>
// );
// }


'use client';

import { useState } from 'react';

export default function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [formData, setFormData] = useState({ name: '', email: '' });
const [message, setMessage] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');

const validateInputs = () => {
if (!formData.name.trim() || !formData.email.trim()) {
setError('Both Name and Email are required');
return false;
}
if (formData.name.length > 50) {
setError('Name must be 50 characters or less');
return false;
}
if (!/\S+@\S+\.\S+/.test(formData.email)) {
setError('Invalid email format');
return false;
}
return true;
};

const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setMessage('');
setError('');


if (!validateInputs()) {
setLoading(false);
return;
}

try {
const res = await fetch('/api/submit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, email }),
body: JSON.stringify(formData),
});

if (!res.ok) throw new Error('Failed to submit');
Expand All @@ -33,35 +126,34 @@ export default function Form() {
};

const handleReset = () => {
setName('');
setEmail('');
setFormData({ name: '', email: '' });
setMessage('');
setError('');
};

return (
<div>
<div style={{ maxWidth: '400px', margin: 'auto', padding: '20px', border: '1px solid #ccc', borderRadius: '8px' }}>
<h1>Form Page</h1>
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit} noValidate>
<input
type="text"
name="name"
placeholder="Enter your name"
value={name}
onChange={(e) => setName(e.target.value)}
value={formData.name}
onChange={handleChange}
/>
<input
type="email"
name="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
value={formData.email}
onChange={handleChange}
/>
<button type="submit" disabled={loading}>
{loading ? 'Submitting...' : 'Submit'}
</button>
<button type="submit">{loading ? 'Submitting...' : 'Submit'}</button>
<button type="button" onClick={handleReset}>Reset</button>
</form>
{message && <p style={{ color: 'green' }}>{message}</p>}
{error && <p style={{ color: 'red' }}>{error}</p>}
<p id="error" style={{ color: 'red', visibility: error ? 'visible' : 'hidden' }}>{error}</p>
<p id="message" style={{ color: 'green', visibility: message ? 'visible' : 'hidden' }}>{message}</p>
</div>
);
}
104 changes: 83 additions & 21 deletions tests/form.spec.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,93 @@
// import { test, expect } from '@playwright/test';

// test('Form submission works correctly', async ({ page }) => {
// await page.goto('/form');

// // Ensure form elements are present
// await expect(page.locator('input[placeholder="Enter your name"]')).toBeVisible();
// await expect(page.locator('input[placeholder="Enter your email"]')).toBeVisible();
// await expect(page.locator('button[type="submit"]')).toHaveText('Submit');

// // Fill out the form
// await page.fill('input[placeholder="Enter your name"]', 'John Doe');
// await page.fill('input[placeholder="Enter your email"]', '[email protected]');

// // Submit the form
// await page.click('button[type="submit"]');

// // Wait for success message
// await expect(page.locator('p')).toHaveText('Thank you, John Doe!');
// });

// test('Shows validation error if fields are missing', async ({ page }) => {
// await page.goto('/form');

// // Try to submit without filling anything
// await page.click('button[type="submit"]');

// // Expect an error message
// await expect(page.locator('p')).toHaveText('Submission failed. Please try again.');
// });

import { test, expect } from '@playwright/test';

test('Form submission works correctly', async ({ page }) => {
await page.goto('/form');
test.describe('Form Submission Tests', () => {
test('✅ Form submission works correctly', async ({ page }) => {
await page.goto('/form');

// Ensure form elements are present
await expect(page.locator('input[placeholder="Enter your name"]')).toBeVisible();
await expect(page.locator('input[placeholder="Enter your email"]')).toBeVisible();
await expect(page.locator('button[type="submit"]')).toHaveText('Submit');
// Check form elements exist
await expect(page.locator('input[name="name"]')).toBeVisible();
await expect(page.locator('input[name="email"]')).toBeVisible();
await expect(page.locator('button[type="submit"]')).toHaveText('Submit');

// Fill out the form
await page.fill('input[placeholder="Enter your name"]', 'John Doe');
await page.fill('input[placeholder="Enter your email"]', '[email protected]');
// Fill out the form
await page.fill('input[name="name"]', 'John Doe');
await page.fill('input[name="email"]', '[email protected]');

// Submit the form
await page.click('button[type="submit"]');
// Submit the form
await page.click('button[type="submit"]');

// Wait for success message
await expect(page.locator('p')).toHaveText('Thank you, John Doe!');
});
// Expect success message
await expect(page.locator('#message')).toHaveText(`Hello John Doe, your form has been submitted successfully!`);
});

test('Shows validation error if fields are missing', async ({ page }) => {
await page.goto('/form');
test('Shows validation error if fields are missing', async ({ page }) => {
await page.goto('/form');

// Try to submit without filling anything
await page.click('button[type="submit"]');
// Click submit without filling anything
await page.click('button[type="submit"]');

// Expect an error message
await expect(page.locator('p')).toHaveText('Submission failed. Please try again.');
});
// Expect validation error
await expect(page.locator('#error')).toHaveText('Both Name and Email are required');
});

test('❌ Shows validation error for invalid email', async ({ page }) => {
await page.goto('/form');

// Fill in the name field
await page.fill('input[name="name"]', 'John Doe');
// Enter an invalid email
await page.fill('input[name="email"]', 'invalid-email');

// Submit the form
await page.click('button[type="submit"]');

// Expect email validation error
await expect(page.locator('#error')).toHaveText('Invalid email format');
});

test('🔄 Reset button clears the form', async ({ page }) => {
await page.goto('/form');

// Fill out the form
await page.fill('input[name="name"]', 'John Doe');
await page.fill('input[name="email"]', '[email protected]');

// Click reset
await page.click('button[type="button"]');

// Expect fields to be cleared
await expect(page.locator('input[name="name"]')).toHaveValue('');
await expect(page.locator('input[name="email"]')).toHaveValue('');
});
});