Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 02 · Media, Tables & FormsChapter 11 of 18
10.
Phase 02Read time ~15 minDifficulty beginner

HTML Form Validation

Form validation is the process of checking whether the data entered by the user is acceptable before the form is submitted.

In this chapter
  • 01Why Do We Need Form Validation?
  • 02Two Types of Validation
  • 03Client-side
  • 04Server-side
  • 05Critical Security Rule
  • 06The required Attribute
  • 07Required Email
  • 08What Happens on Submit?
  • 09minlength
  • 10maxlength
  • 11Combining minlength and maxlength
  • 12min and max
  • 13step
  • 14step With Range
  • 15Email Validation
  • 16Important nuance
  • 17URL Validation
  • 18Number Validation
  • 19Date Validation
  • 20Time Validation
  • 21The pattern Attribute
  • 22Pattern for a 10-Digit Number
  • 23But remember
  • 24Pattern for Username
  • 25Important pattern Detail
  • 26required + pattern
  • 27Validation of Radio Buttons
  • 28Validation of Checkboxes
  • 29Required Select
  • 30Required Textarea
  • 31Validation Example
  • 32The Constraint Validation API
  • 33checkValidity()
  • 34form.checkValidity()
  • 35reportValidity()
  • 36setCustomValidity()
  • 37validity
  • 38Example: Understanding validity
  • 39valid and invalid CSS States
  • 40:user-valid and :user-invalid
  • 41novalidate
  • 42formnovalidate
  • 43Validation Flow
  • 44Client-Side vs Server-Side Validation
  • 45HTML Validation Is Not Business Logic
  • 46Common Validation Mistakes
  • 47Mistake 1 — Only validating in HTML
  • 48Mistake 2 — Trusting pattern
  • 49Mistake 3 — Using type="number" for everything numeric
  • 50Mistake 4 — Using an overly strict email regex
  • 51Complete Professional Validation Example
  • 52Validation Attributes Cheat Sheet
  • 53Interview Questions
  • 54Q1. What is HTML form validation?
  • 55Q2. What does required do?
  • 56Q3. Difference between min and minlength?
  • 57Q4. Difference between maxlength and max?
  • 58Q5. What is pattern?
  • 59Q6. What is checkValidity()?
  • 60Q7. What is reportValidity()?
  • 61Q8. What does setCustomValidity() do?
  • 62Q9. Can HTML validation replace backend validation?
  • 63Q10. What is novalidate?
  • 64Mini Project — Professional Registration Form
  • 65Chapter 9 — Final Mental Model
  • 66Next Chapter
  • 67Chapter 10 — Semantic HTML
In this chapter (67 sections)
01Why Do We Need Form Validation?02Two Types of Validation03Client-side04Server-side05Critical Security Rule06The required Attribute07Required Email08What Happens on Submit?09minlength10maxlength11Combining minlength and maxlength12min and max13step14step With Range15Email Validation16Important nuance17URL Validation18Number Validation19Date Validation20Time Validation21The pattern Attribute22Pattern for a 10-Digit Number23But remember24Pattern for Username25Important pattern Detail26required + pattern27Validation of Radio Buttons28Validation of Checkboxes29Required Select30Required Textarea31Validation Example32The Constraint Validation API33checkValidity()34form.checkValidity()35reportValidity()36setCustomValidity()37validity38Example: Understanding validity39valid and invalid CSS States40:user-valid and :user-invalid41novalidate42formnovalidate43Validation Flow44Client-Side vs Server-Side Validation45HTML Validation Is Not Business Logic46Common Validation Mistakes47Mistake 1 — Only validating in HTML48Mistake 2 — Trusting pattern49Mistake 3 — Using type="number" for everything numeric50Mistake 4 — Using an overly strict email regex51Complete Professional Validation Example52Validation Attributes Cheat Sheet53Interview Questions54Q1. What is HTML form validation?55Q2. What does required do?56Q3. Difference between min and minlength?57Q4. Difference between maxlength and max?58Q5. What is pattern?59Q6. What is checkValidity()?60Q7. What is reportValidity()?61Q8. What does setCustomValidity() do?62Q9. Can HTML validation replace backend validation?63Q10. What is novalidate?64Mini Project — Professional Registration Form65Chapter 9 — Final Mental Model66Next Chapter67Chapter 10 — Semantic HTML

For example:

User enters:
Email → anubhav
        ↓
Is this a valid email?
        ↓
       ❌
        ↓
Show validation error

HTML provides a powerful built-in validation system, so you can perform many common validations without JavaScript.


1. Why Do We Need Form Validation?#

Imagine a registration form:

Name:
[                  ]
 
Email:
[                  ]
 
Age:
[                  ]
 
Password:
[                  ]

A user could enter:

Name:     ""
Email:    hello
Age:      -50
Password: ""

Obviously, your application probably shouldn't accept all of these values.

Validation helps enforce rules such as:

Name → required
Email → valid email format
Age → between 18 and 100
Password → minimum 8 characters
Username → maximum 20 characters

2. Two Types of Validation#

There are two major layers:

             FORM VALIDATION
                    │
          ┌─────────┴─────────┐
          │                   │
          ▼                   ▼
   Client-side             Server-side
   validation              validation

Client-side#

Runs in the browser.

Examples:

required
minlength
maxlength
pattern
type="email"
min
max

Server-side#

Runs on your backend.

For example:

Browser
   ↓
Next.js API
   ↓
Validate data
   ↓
Database

3. Critical Security Rule#

Never assume:

"The browser validated it, therefore the data is safe."

A malicious user can bypass browser validation.

For example, someone can send an HTTP request directly to your backend without using your HTML form.

Therefore:

HTML validation
      +
Server validation
      +
Authorization
      +
Business rules

For security-sensitive applications, server-side validation is mandatory.


4. The required Attribute#

The simplest validation rule is:

<input
    type="text"
    name="username"
    required
>

This means:

The user must provide a value.

Without:

required

the field can normally be empty.


5. Required Email#

<label for="email">
    Email
</label>
 
<input
    type="email"
    id="email"
    name="email"
    required
>

Now the browser checks both:

Field is not empty
        +
Value matches email-type constraints

6. What Happens on Submit?#

Suppose:

<input
    type="email"
    name="email"
    required
>

User clicks:

[ Submit ]

without entering anything.

The browser can prevent submission and display a native validation message.

Conceptually:

Email
[                 ]
 
      ↓ Submit
 
❌ Please fill out this field.

The exact message depends on the browser and user's language.


7. minlength#

minlength specifies the minimum number of characters.

Example:

<input
    type="text"
    name="username"
    minlength="3"
>

This means:

Minimum = 3 characters

So:

ab       ❌
abc      ✅
anubhav  ✅

8. maxlength#

maxlength specifies the maximum number of characters.

<input
    type="text"
    name="username"
    maxlength="20"
>

Maximum:

20 characters

This can be useful for:

  • Usernames
  • Names
  • Titles
  • Short descriptions
  • Phone-related fields where appropriate

9. Combining minlength and maxlength#

<input
    type="text"
    name="username"
    minlength="3"
    maxlength="20"
    required
>

Now the field must satisfy:

Required
AND
minimum 3 characters
AND
maximum 20 characters

10. min and max#

For numeric controls:

<input
    type="number"
    name="age"
    min="18"
    max="100"
>

Allowed range:

18 ───────────────── 100

Examples:

17    ❌
18    ✅
25    ✅
100   ✅
101   ❌

11. step#

step specifies the allowed increments.

Example:

<input
    type="number"
    name="price"
    min="0"
    step="0.01"
>

This supports values such as:

10
10.01
10.50
99.99

For integers:

<input
    type="number"
    min="0"
    max="100"
    step="1"
>

12. step With Range#

For a range slider:

<input
    type="range"
    name="volume"
    min="0"
    max="100"
    step="10"
>

Possible values:

0
10
20
30
40
...
100

13. Email Validation#

HTML provides a specialized input type:

<input type="email">

Example:

<label for="email">
    Email
</label>
 
<input
    type="email"
    id="email"
    name="email"
    required
>

The browser can detect values that don't satisfy its email-type constraint.

For example:

hello          → likely invalid
hello@         → likely invalid
hello@example.com → valid format

Important nuance#

"Valid email syntax" is not the same thing as:

"This email address actually exists."

HTML cannot determine whether an email inbox exists.


14. URL Validation#

Use:

<input
    type="url"
    name="website"
>

Example:

<label for="website">
    Website
</label>
 
<input
    type="url"
    id="website"
    name="website"
>

The browser applies URL-type constraints.


15. Number Validation#

<input
    type="number"
    name="age"
    min="18"
    max="100"
    required
>

This gives the browser information about the expected input.


16. Date Validation#

You can also constrain dates.

Example:

<input
    type="date"
    name="dob"
    min="1950-01-01"
    max="2010-12-31"
>

The browser can use those constraints when validating the field.


17. Time Validation#

Similarly:

<input
    type="time"
    name="appointment"
    min="09:00"
    max="18:00"
>

This describes an allowed time range.


18. The pattern Attribute#

pattern allows you to specify a regular-expression-based constraint.

Example:

<input
    type="text"
    name="username"
    pattern="[A-Za-z0-9]+"
>

This says the value should contain only:

A-Z
a-z
0-9

So:

anubhav123    ✅
Warrior2026   ✅
anubhav_123   ❌
anubhav@123   ❌

19. Pattern for a 10-Digit Number#

A simple example:

<input
    type="tel"
    name="phone"
    pattern="[0-9]{10}"
>

This describes exactly 10 digits.

Examples:

9876543210    ✅
123456789     ❌
12345678901   ❌
98765abc10    ❌

But remember#

Phone-number formats differ internationally.

For a production application, don't blindly assume every phone number is exactly 10 digits.


20. Pattern for Username#

Suppose your application wants:

3–15 characters
letters, numbers and underscore

You might use:

<input
    type="text"
    name="username"
    pattern="[A-Za-z0-9_]{3,15}"
    required
>

Examples:

warrior123      ✅
anubhav         ✅
dev_user        ✅
ab              ❌
hello-world     ❌

21. Important pattern Detail#

Modern HTML pattern matching uses the browser's regular-expression semantics, with the pattern effectively required to match the whole value, not merely find a substring.

Therefore, when designing patterns, think in terms of:

Does the entire value satisfy my rule?

rather than:

Does some part of the value match?

22. required + pattern#

These are often combined:

<input
    type="text"
    name="username"
    required
    pattern="[A-Za-z0-9_]{3,15}"
>

Now:

empty
→ ❌ required
 
abc
→ ✅
 
abc_123
→ ✅
 
ab
→ ❌ too short
 
hello-world
→ ❌ invalid pattern

23. Validation of Radio Buttons#

You can also require a radio group to have a selection.

Example:

<fieldset>
 
    <legend>Choose a plan</legend>
 
    <label>
        <input
            type="radio"
            name="plan"
            value="free"
            required
        >
        Free
    </label>
 
    <label>
        <input
            type="radio"
            name="plan"
            value="pro"
        >
        Pro
    </label>
 
</fieldset>

The group needs a valid selection before submission.


24. Validation of Checkboxes#

A checkbox can also be required.

For example:

<label>
    <input
        type="checkbox"
        name="terms"
        value="accepted"
        required
    >
 
    I agree to the Terms and Conditions
</label>

The user must check it before submitting.

This is common for:

☐ I agree to Terms and Conditions

25. Required Select#

Example:

<select
    name="country"
    required
>
    <option value="">
        Select a country
    </option>
 
    <option value="india">
        India
    </option>
 
    <option value="usa">
        USA
    </option>
</select>

The initial option has:

value=""

so it doesn't satisfy the required selection.

A more robust pattern is:

<select name="country" required>
 
    <option
        value=""
        selected
        disabled
    >
        Select a country
    </option>
 
    <option value="india">
        India
    </option>
 
    <option value="usa">
        USA
    </option>
 
</select>

26. Required Textarea#

<textarea
    name="message"
    required
></textarea>

The user must provide content before submitting.


27. Validation Example#

Let's build a small registration form.

<form action="/register" method="post">
 
    <div>
 
        <label for="username">
            Username
        </label>
 
        <input
            type="text"
            id="username"
            name="username"
            minlength="3"
            maxlength="20"
            pattern="[A-Za-z0-9_]+"
            required
        >
 
    </div>
 
    <div>
 
        <label for="email">
            Email
        </label>
 
        <input
            type="email"
            id="email"
            name="email"
            required
        >
 
    </div>
 
    <div>
 
        <label for="age">
            Age
        </label>
 
        <input
            type="number"
            id="age"
            name="age"
            min="18"
            max="100"
            required
        >
 
    </div>
 
    <div>
 
        <label for="password">
            Password
        </label>
 
        <input
            type="password"
            id="password"
            name="password"
            minlength="8"
            required
        >
 
    </div>
 
    <button type="submit">
        Register
    </button>
 
</form>

Now HTML itself handles many basic constraints.


28. The Constraint Validation API#

HTML validation becomes even more powerful when JavaScript is involved.

Browsers expose the:

Constraint Validation API

This allows JavaScript to inspect and trigger validation.

Important methods include:

checkValidity()
reportValidity()
setCustomValidity()

29. checkValidity()#

Suppose:

<input
    id="email"
    type="email"
    required
>

JavaScript can do:

const email = document.querySelector("#email");
 
console.log(email.checkValidity());

It returns:

true

if the element satisfies its constraints.

Otherwise:

false

30. form.checkValidity()#

You can validate the entire form:

const form = document.querySelector("form");
 
if (form.checkValidity()) {
    console.log("Form is valid");
} else {
    console.log("Form is invalid");
}

This is useful when building custom application logic.


31. reportValidity()#

reportValidity() checks validity and asks the browser to report validation errors to the user.

Example:

const form = document.querySelector("form");
 
form.reportValidity();

Conceptually:

Form
 ↓
Validation
 ↓
Invalid?
 ↓
Browser displays validation message

32. setCustomValidity()#

This allows JavaScript to define a custom validation error.

Example:

const username = document.querySelector("#username");
 
username.setCustomValidity(
    "This username is already taken."
);

Now the field is considered invalid.

To clear the custom error:

username.setCustomValidity("");

This is important:

non-empty custom message
→ invalid
 
empty string
→ custom error cleared

33. validity#

Form controls also expose a:

validity

property.

Example:

const input = document.querySelector("#email");
 
console.log(input.validity);

It provides information about different validation states.

Common properties include:

valueMissing
typeMismatch
patternMismatch
tooLong
tooShort
rangeUnderflow
rangeOverflow
stepMismatch
badInput
customError
valid
invalid

34. Example: Understanding validity#

Suppose:

<input
    type="email"
    id="email"
    required
>

If the user leaves it empty:

email.validity.valueMissing

can be:

true

If they enter something that doesn't satisfy the email constraint:

email.validity.typeMismatch

can indicate the problem.

This lets JavaScript build more customized validation experiences.


35. valid and invalid CSS States#

CSS provides pseudo-classes:

input:valid {
    /* valid state */
}
 
input:invalid {
    /* invalid state */
}

For example:

input:invalid {
    border: 2px solid red;
}
 
input:valid {
    border: 2px solid green;
}

We aren't focusing on CSS yet, but understand the concept:

HTML constraint
      ↓
Validity state
      ↓
CSS can react

36. :user-valid and :user-invalid#

Modern browsers also support user-interaction-aware validation pseudo-classes such as:

input:user-invalid

and:

input:user-valid

These can help avoid immediately showing every validation state before the user has interacted with the field.

Browser support and exact behavior can vary, so production applications should test their target browsers.


37. novalidate#

You learned this in the previous chapter:

<form novalidate>

It disables the browser's automatic constraint-validation step when submitting that form.

For example:

<form
    action="/register"
    method="post"
    novalidate
>

Now your application can implement a custom validation flow.

But:

novalidate

does not mean:

"Don't validate anything."

It means:

Don't use the browser's normal interactive constraint-validation behavior for form submission.

Your server should still validate.


38. formnovalidate#

You can also disable constraint validation for a particular submit button.

<form>
 
    <input
        type="email"
        name="email"
        required
    >
 
    <button type="submit">
        Submit
    </button>
 
    <button
        type="submit"
        formnovalidate
    >
        Save Draft
    </button>
 
</form>

This can be useful when:

Submit
→ requires complete valid form
 
Save Draft
→ allows incomplete form

Very useful in real applications.


39. Validation Flow#

A useful mental model:

             USER
               │
               ▼
          Enters data
               │
               ▼
       HTML constraints
               │
       ┌───────┴────────┐
       │                │
      Valid           Invalid
       │                │
       ▼                ▼
   Continue         Show error
       │
       ▼
    Submit
       │
       ▼
    Server
       │
       ▼
Server-side validation
       │
   ┌───┴────┐
   │        │
 Valid    Invalid
   │        │
   ▼        ▼
Process   Reject

40. Client-Side vs Server-Side Validation#

This distinction is extremely important for interviews.

Client-side Server-side
Runs in browser Runs on server
Fast feedback Trusted validation layer
Better UX Security/business rules
Can be bypassed Must be enforced
Uses HTML/JS Uses backend code

For example:

HTML:
age >= 18

is good UX.

But your backend should also verify:

age >= 18

because the client cannot be trusted.


41. HTML Validation Is Not Business Logic#

Suppose your HTML says:

<input
    type="number"
    min="18"
>

That's useful.

But imagine your business rule is:

Only users aged 21+ can purchase this product.

HTML alone shouldn't be treated as the authoritative business rule.

The backend must enforce:

age >= 21

The browser is a user interface, not your security boundary.


42. Common Validation Mistakes#

Mistake 1 — Only validating in HTML#

Browser validation
      ↓
Database

Bad architecture.

Better:

Browser validation
      ↓
Server validation
      ↓
Authorization
      ↓
Database

Mistake 2 — Trusting pattern#

Suppose:

<input
    pattern="[0-9]{10}"
>

A malicious client can bypass it.

Server validation is still necessary.


Mistake 3 — Using type="number" for everything numeric#

Phone numbers aren't really mathematical numbers.

For example:

+91 9876543210

or:

0012345678

can make number inappropriate.

For phone numbers:

<input type="tel">

is generally more semantically appropriate.


Mistake 4 — Using an overly strict email regex#

Don't try to replace proper email handling with a giant regex unless you have a very specific requirement.

For normal browser-side validation:

<input type="email">

is often the right starting point.

Then perform appropriate server-side validation.


43. Complete Professional Validation Example#

<form action="/register" method="post">
 
    <fieldset>
 
        <legend>Account Information</legend>
 
        <p>
 
            <label for="username">
                Username
            </label>
 
            <input
                type="text"
                id="username"
                name="username"
                minlength="3"
                maxlength="20"
                pattern="[A-Za-z0-9_]+"
                autocomplete="username"
                required
            >
 
        </p>
 
        <p>
 
            <label for="email">
                Email
            </label>
 
            <input
                type="email"
                id="email"
                name="email"
                autocomplete="email"
                required
            >
 
        </p>
 
        <p>
 
            <label for="password">
                Password
            </label>
 
            <input
                type="password"
                id="password"
                name="password"
                minlength="8"
                autocomplete="new-password"
                required
            >
 
        </p>
 
    </fieldset>
 
    <fieldset>
 
        <legend>Personal Information</legend>
 
        <p>
 
            <label for="age">
                Age
            </label>
 
            <input
                type="number"
                id="age"
                name="age"
                min="18"
                max="100"
                required
            >
 
        </p>
 
        <p>
 
            <label for="website">
                Website
            </label>
 
            <input
                type="url"
                id="website"
                name="website"
            >
 
        </p>
 
    </fieldset>
 
    <label>
 
        <input
            type="checkbox"
            name="terms"
            value="accepted"
            required
        >
 
        I agree to the Terms and Conditions
 
    </label>
 
    <br><br>
 
    <button type="submit">
        Create Account
    </button>
 
</form>

This form uses:

required
minlength
maxlength
pattern
min
max
type validation
autocomplete
checkbox validation

without JavaScript.


44. Validation Attributes Cheat Sheet#

Attribute Purpose
required Value must be provided
minlength Minimum text length
maxlength Maximum text length
min Minimum numeric/date value
max Maximum numeric/date value
step Allowed increments
pattern Pattern constraint
type="email" Email-type constraint
type="url" URL-type constraint
accept File-type hint
multiple Multiple values/files
novalidate Disable interactive constraint validation for form submission
formnovalidate Disable it for a specific submit button

45. Interview Questions#

Q1. What is HTML form validation?#

It is the process of checking whether form values satisfy specified constraints before submission.


Q2. What does required do?#

It prevents a control from satisfying the required constraint when its value is missing.


Q3. Difference between min and minlength?#

min
→ minimum value
 
minlength
→ minimum number of characters

Example:

<input type="number" min="18">

versus:

<input type="text" minlength="8">

Q4. Difference between maxlength and max?#

maxlength
→ maximum number of characters
 
max
→ maximum value

Q5. What is pattern?#

A constraint based on a regular expression.


Q6. What is checkValidity()?#

It checks whether a form control or form satisfies its validation constraints.


Q7. What is reportValidity()?#

It checks validity and asks the browser to report validation problems to the user.


Q8. What does setCustomValidity() do?#

It sets a custom validation error message.

input.setCustomValidity("Username already exists");

Clear it with:

input.setCustomValidity("");

Q9. Can HTML validation replace backend validation?#

No.

Client-side validation can be bypassed.


Q10. What is novalidate?#

It tells the browser not to perform its normal interactive constraint validation when submitting that form.


46. Mini Project — Professional Registration Form#

Build a registration page containing:

              CREATE ACCOUNT
 
Username
[________________________]
 
Email
[________________________]
 
Password
[________________________]
 
Confirm Password
[________________________]
 
Age
[________________________]
 
Phone
[________________________]
 
Country
[ Select Country ▼ ]
 
Gender
○ Male
○ Female
○ Other
 
Skills
☐ HTML
☐ CSS
☐ JavaScript
☐ React
 
☐ I agree to Terms
 
[ Create Account ]

Apply these constraints:

Username
→ required
→ 3–20 characters
→ letters/numbers/underscore
 
Email
→ required
→ email type
 
Password
→ required
→ minimum 8 characters
 
Age
→ required
→ 18–100
 
Country
→ required
 
Gender
→ required
 
Terms
→ required

Try doing the entire project with HTML only first.

Then later, JavaScript can enhance the experience.


Chapter 9 — Final Mental Model#

HTML validation is essentially:

             FORM
               │
               ▼
        Define constraints
               │
       ┌───────┴────────┐
       │                │
     Valid            Invalid
       │                │
       ▼                ▼
 Continue           Error shown
       │
       ▼
    Submit
       │
       ▼
     Server
       │
       ▼
Validate again

The most important principle is:

Browser validation improves user experience; server-side validation protects your application.


Next Chapter#

Chapter 10 — Semantic HTML#

Next we'll move from forms into modern HTML5 semantics and learn:

  • What semantic HTML means
  • <header>
  • <nav>
  • <main>
  • <section>
  • <article>
  • <aside>
  • <footer>
  • <figure>
  • <figcaption>
  • <address>
  • Semantic vs non-semantic elements
  • <div> vs <section>
  • <section> vs <article>
  • Page landmarks
  • Accessibility benefits
  • SEO benefits
  • Building a complete semantic website structure
  • Common semantic HTML mistakes
  • Professional HTML5 page architecture
  • Interview questions

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 8 — Advanced Form ControlsNext ChapterChapter 10 — Semantic HTML
PrevNext