
Form in HTML Full details with suitable example
What is a <form>?
A <form> is an HTML element that groups controls (inputs, selects, textareas, buttons) used to collect user input and send it to a server (or handle it on the client). Forms are the primary way for users to submit data (login, search, register, upload files, etc.).
- Forms are used for data gathering in webpage.
- It provides full range of GUI control.
- It can automatically save data by using submit button.
- An html forms contain form element are different types of elements.
Like – textfield, check box, radio button, submit button etc.
<form action=”URL” method=”GET|POST”>
<!– inputs and controls –>
</form>
Attributes of form tag :
This attributes specified the https method get or post to be used when submitting form data.
<form method=”GET / POST “>
When to use GET :-
- This is default method when submitting data.
- When GET is used the submitted form data will be visible in the page address field.
- The length of URL is limited about 3000 character.
- Never use GET to send sensitive data because data is visible in URL.
- GET is better for non secure data.
- Useful for form submission there a user on to bokmark the result.
When to use POST :-
- Always use POST if the form data contains sensitive or personal information.
- The POST method does not display the submitted the data in the page Address field.
- POST has no size limitation and can be used to send large amount of data.
- It can not be bookmark.
Name attributes :-
It is used to set the name of form.
Action attributes :-
It is used to define action to be perform.
When the form is submitted.
<form action= action.php”>
</form>
Target attributes:
The target attributes specified in the submitted result will open in a new browser tab a frame or in current window.
The default value is _self which means the for will be submitted in the current window.
To make the form result opon in a new browser tab use the value _blank.
Example :
<form action=”action-page.php”target=”_blank”>
</form>
Most commonly used tag by creating a form :-
1. <input>
2. <text area>
3. <select>
1. <input>
The most important tag in a form is the input tag.
The input tag is used to select the user information.
Using the input tag, you can add control such as: text input, radio button, check box, contr0ls, submit button, Cancel button, reset button and so on.
1.1 Text input:
First name <input type=”text” Name = “First”> <b>
Last name:  </b> <input type=”text” Name=”last”>
1.2 Radio button:
<input type=”radio” name = “Gender “Value = “Male” checked> male // checked means automatic select Male
<input type=”radio” name = “Gender” value=”female “>Female.
1.3 Check box:
<input type=”check box” name=”Hobbies ” valus = “Singing”> Singing
<input type=”check box” name=”Hobbies” value=”Dancing”> Dancing
1.4 Submit button:
<input type=”submit” name = “btn submit” value= “SUBMIT”>
1.5 Reset button:
<input type = “Reset” name = “btn reset” value= “RESET”>
1.6 Cancel button:
<input type = “Cancel” name=”btn cancel” value=”CANCEL”>
1.7 Password button:
<input type = “Password” name = “Password”>
2. <text area>
Text area defined as multiline input field.
There are two attributes in text area-
(1) rows
(ii) Cols (Column)
The raws attribuides specified the visible number of lines in text area and cols attributes specified the visible width the text area.
<textarea name = “feedback” rows=”30″ cols=”10″>
Hello Guys Please Visit my website : www.csaccept.com
<textarea>
3. <select>
Select element define the drop down list.
<option> element define and option that can be selected.
<select name=”City”>
<option value=”Prayagraj”> Prayagraj selected</option> // selected means automatic select option.
<option value = “Mirzapur”> Mirzapur </option>-
</select>
Important <form> attributes: 1. action — URL where the form data is sent when submitted. If omitted, data is submitted to the current page. 2. method — HTTP method: "GET" (sends data in URL query string) or "POST" (sends in request body). Use POST for sensitive or large data. 3. enctype — encoding type used to submit the form. Common values: 4. application/x-www-form-urlencoded (default) 5. multipart/form-data — required for file uploads (<input type="file">) 6. text/plain — rarely used 7. target — where to display response: _self, _blank, _parent, _top, or a named iframe. 8. autocomplete — "on" or "off"; whether browser can autofill fields. 9. accept-charset — character encodings (e.g., "UTF-8"). 10. novalidate — if present, disables built-in HTML validation on submit. 11. name / id — forms can have names/IDs for JS or server-side reference. Common form controls and attributes 1. Inputs (<input>) 2. Common type values: 3. text — single-line text 4. password — obscured text 5. email — email address (built-in validation) 6. tel — telephone number 7. url — URL 8. number — numeric input 9. range — slider 10. checkbox — boolean option (can use many with same name) 11. radio — one-of-many option (use same name for group) 12. file — file upload 13. date, time, datetime-local, month, week — date/time pickers 14. color — color picker 15. search — search field 16. hidden — invisible data sent with the form 17. submit / button / reset — buttons (submit sends the form) 18. Common attributes for inputs: 19. name — required for form data to be sent to server (key name) 20. id — for <label for="..."> association and JS/CSS targeting 21. value — initial value 22. placeholder — hint text inside the control 23. required — makes the field mandatory 24. readonly — cannot be changed by user 25. disabled — not editable and not submitted 26. min, max, step — for number, range, date, etc. 27. pattern — regex pattern for validation 28. maxlength, minlength — length constraints 29. multiple — for file (allow many files) or <select> (allow multiple chosen) 30. accept — for file inputs, allowed MIME types/extensions (e.g., accept="image/*,.pdf") 31. autofocus — field gets focus when page loads 32. autocomplete — field-level autofill preference (name="email" etc.)
<label>
Use <label> to connect text to a control. Either wrap the control:
<label>Username: <input type=”text” name=”username”></label>
or use for:
<label for=”username”>Username</label>
<input id=”username” name=”username” type=”text”>
Labels improve accessibility and enlarge the clickable area.
Client-side validation attributes
1. required — field must be filled
2. pattern — regex match (pattern=”^[A-Za-z0-9_]+$”)
3. min, max, step, minlength, maxlength
4. Input types like email, url, number provide built-in validation
5. Use novalidate on <form> to disable
For custom validation and better UX, use JavaScript to customize messages and handle complex rules.
Accessibility best practices
1. Use <label> for every input (or aria-label/aria-labelledby if needed).
2. Group related controls with <fieldset> + <legend>.
3. Provide helper text with aria-describedby referencing an ID of a small help <div>.
4. Ensure keyboard navigability (tab order, meaningful tabindex if required).
5. Use clear error messages and associate them with inputs (aria-invalid, aria-describedby).
Security & server-side notes
1. Never trust client-side validation; always validate on the server.
2. Escape and sanitize inputs to prevent SQL injection, XSS.
3. Use CSRF protection (tokens) for state-changing POST requests.
4. Use HTTPS to protect data in transit.
5. For file uploads, validate file type/size on server and store outside webroot or rename files.
Complete practical example
A complete HTML form (with basic styling) and a minimal PHP handler example. This example demonstrates many input types, validation attributes, multipart/form-data for file upload, accessibility, and a simple PHP receiver.
Save the HTML as form-example.html and the PHP as process-form.php on a PHP-enabled server (e.g., XAMPP). This is a simple demo — for production, add stronger server validation and CSRF protection.
form-example.html
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<meta name=”viewport” content=”width=device-width,initial-scale=1″ />
<title>Example HTML Form</title>
<style>
body { font-family: system-ui, Arial; padding: 24px; max-width: 900px; margin: auto; }
label { display: block; margin-top: 12px; font-weight: 600; }
input, select, textarea { width: 100%; padding: 8px; margin-top: 6px; box-sizing: border-box; }
fieldset { border: 1px solid #ccc; padding: 12px; margin-top: 16px; }
.row { display:flex; gap:12px; }
.col { flex:1; }
.small { width: auto; display:inline-block; }
.hint { font-size: 0.9em; color: #555; }
button { margin-top: 14px; padding: 10px 16px; font-size: 1rem; }
.required-star::after { content:” *”; color: #c00; }
</style>
</head>
<body>
<h1>Registration form (example)</h1>
<form action=”process-form.php” method=”post” enctype=”multipart/form-data” autocomplete=”on” accept-charset=”UTF-8″>
<fieldset>
<legend>Personal information</legend>
<label for=”fullname” class=”required-star”>Full name</label>
<input id=”fullname” name=”fullname” type=”text” placeholder=”Your full name” required minlength=”3″ maxlength=”100″ />
<div class=”row”>
<div class=”col”>
<label for=”email” class=”required-star”>Email</label>
<input id=”email” name=”email” type=”email” placeholder=”you@example.com” required />
</div>
<div class=”col”>
<label for=”phone”>Phone</label>
<input id=”phone” name=”phone” type=”tel” placeholder=”+91-9876543210″ pattern=”^\+?\d{7,15}$” />
<div class=”hint”>Include country code (optional). Digits only.</div>
</div>
</div>
<label for=”password” class=”required-star”>Password</label>
<input id=”password” name=”password” type=”password” required minlength=”6″ />
<label for=”bio”>Short bio</label>
<textarea id=”bio” name=”bio” rows=”4″ maxlength=”500″ placeholder=”Tell us a bit about yourself…”></textarea>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Gender</label>
<label><input type=”radio” name=”gender” value=”male”> Male</label>
<label><input type=”radio” name=”gender” value=”female”> Female</label>
<label><input type=”radio” name=”gender” value=”other”> Other</label>
<label for=”skills”>Skills (select multiple)</label>
<select id=”skills” name=”skills[]” multiple size=”4″>
<option value=”html”>HTML</option>
<option value=”css”>CSS</option>
<option value=”js”>JavaScript</option>
<option value=”php”>PHP</option>
</select>
<label for=”experience”>Years of experience</label>
<input id=”experience” name=”experience” type=”number” min=”0″ max=”50″ step=”1″ value=”0″ class=”small” />
<label for=”salary”>Expected salary (₹)</label>
<input id=”salary” name=”salary” type=”range” min=”100000″ max=”2000000″ step=”10000″ />
</fieldset>
<fieldset>
<legend>Files & confirmation</legend>
<label for=”resume”>Upload resume (PDF, max 2MB)</label>
<input id=”resume” name=”resume” type=”file” accept=”application/pdf” />
<label>
<input type=”checkbox” name=”subscribe” value=”yes”> Subscribe to newsletter
</label>
<label for=”website”>Personal website</label>
<input id=”website” name=”website” type=”url” placeholder=”https://example.com” />
</fieldset>
<div style=”margin-top:16px;”>
<button type=”submit”>Submit</button>
<button type=”reset” style=”margin-left:8px;”>Reset</button>
</div>
</form>
</body>
</html>
process-form.php (very simple example)
<?php
// process-form.php
// Simple demo: DO NOT use in production without proper sanitization and security
function safe($s) {
return htmlspecialchars(trim($s), ENT_QUOTES, ‘UTF-8’);
}
if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) {
$fullname = isset($_POST[‘fullname’]) ? safe($_POST[‘fullname’]) : ”;
$email = isset($_POST[’email’]) ? safe($_POST[’email’]) : ”;
$phone = isset($_POST[‘phone’]) ? safe($_POST[‘phone’]) : ”;
$password = isset($_POST[‘password’]) ? $_POST[‘password’] : ”;
$bio = isset($_POST[‘bio’]) ? safe($_POST[‘bio’]) : ”;
$gender = isset($_POST[‘gender’]) ? safe($_POST[‘gender’]) : ”;
$skills = isset($_POST[‘skills’]) ? $_POST[‘skills’] : [];
$experience = isset($_POST[‘experience’]) ? (int)$_POST[‘experience’] : 0;
$subscribe = isset($_POST[‘subscribe’]) ? ‘yes’ : ‘no’;
$website = isset($_POST[‘website’]) ? safe($_POST[‘website’]) : ”;
// File handling (if uploaded)
if (!empty($_FILES[‘resume’][‘name’])) {
$fileTmp = $_FILES[‘resume’][‘tmp_name’];
$fileName = basename($_FILES[‘resume’][‘name’]);
$fileSize = $_FILES[‘resume’][‘size’];
$fileType = mime_content_type($fileTmp);
// Basic checks
if ($fileType !== ‘application/pdf’) {
die(‘Only PDF resumes accepted.’);
}
if ($fileSize > 2 * 1024 * 1024) {
die(‘File too large. Max 2MB.’);
}
// Move to safe location (ensure ‘uploads’ exists and is writeable)
$target = __DIR__ . ‘/uploads/’ . time() . ‘-‘ . preg_replace(‘/[^A-Za-z0-9_.-]/’, ‘_’, $fileName);
if (!move_uploaded_file($fileTmp, $target)) {
die(‘Failed to save uploaded file.’);
}
}
// Example: show submitted values (for demo only)
echo “<h2>Form submitted</h2>”;
echo “<p><strong>Full name:</strong> ” . $fullname . “</p>”;
echo “<p><strong>Email:</strong> ” . $email . “</p>”;
echo “<p><strong>Phone:</strong> ” . $phone . “</p>”;
echo “<p><strong>Gender:</strong> ” . $gender . “</p>”;
echo “<p><strong>Skills:</strong> ” . htmlspecialchars(implode(‘, ‘, $skills)) . “</p>”;
echo “<p><strong>Experience:</strong> ” . $experience . ” years</p>”;
echo “<p><strong>Subscribe:</strong> ” . $subscribe . “</p>”;
echo “<p><strong>Website:</strong> ” . $website . “</p>”;
// NEVER store plain passwords. Use password_hash() when saving to DB:
if (!empty($password)) {
$hash = password_hash($password, PASSWORD_DEFAULT);
echo “<p>Password hash (store this): $hash</p>”;
}
// Server-side validation & DB insertion would go here (use prepared statements)
} else {
echo “Please submit the form.”;
}
?>
Quick checklist for building forms
1. Use meaningful name attributes — these keys are what your server receives.
2. Always validate on server even if you validate on client.
3. Use HTTPS and CSRF protections.
4. Provide accessible labels and error messages.
5. Use enctype=”multipart/form-data” for uploads.
6. For file uploads: limit size and allowed types, store safely.
7. Prefer POST for operations that change state or include sensitive info.
8. Use required, pattern, min, max for basic HTML validation.
9. For production, sanitize, validate, and use prepared statements for DB writes.