React Form Submission and Validation
Use the submit event, native constraints and a clear result message for a local preview.
How it works
A form’s submit event covers keyboard submission as well as a button click. Prevent the default navigation only when your handler intentionally takes over. Native required and range constraints can block invalid submission before the handler runs. The handler should still check parsed values because a real server cannot trust browser constraints. This example reads FormData, validates an integer quantity and displays a local summary without any network request.
Run the code
Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.
No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.
Example
import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';
function App() {
const [message, setMessage] = useState('No preview yet');
function submit(event) {
event.preventDefault();
const data = new FormData(event.currentTarget);
const quantity = Number(data.get('quantity'));
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 3) {
setMessage('Choose 1 to 3 items');
return;
}
setMessage('Local preview: ' + quantity + ' items. Not reserved.');
}
return (
<main>
<h1>Neighbourhood lending desk</h1>
<form onSubmit={submit}>
<label>
Quantity, 1 to 3
<input
name="quantity"
type="number"
min="1"
max="3"
step="1"
required
defaultValue="1"
/>
</label>
<button type="submit">Preview request</button>
</form>
<output aria-live="polite">{message}</output>
</main>
);
}
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
);
Expected result
Submitting two produces “Local preview: 2 items. Not reserved.” Invalid values do not produce a success message.
FormData uses control names, not their IDs. Number parsing and integer validation state the accepted contract explicitly. Native browser feedback handles these simple constraints; complex errors need field associations and focus planning. A production request also needs authorization, server validation, duplicate handling and a real response before claiming a reservation.
For API contracts and version differences, use React’s official documentation.