JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 13: Forms and ValidationLesson 63 of 150About 40 minutes

Lesson 63: Native browser validation

01Opening question

Before writing any validation code, what can the browser already check for you?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

required and type="email" are checked by the browser. JavaScript can ask whether a field is valid and why not.

const email = document.querySelector("#email");
console.log(email.checkValidity(), email.validity.valueMissing);
email.value = "not-an-email";
console.log(email.checkValidity(), email.validity.typeMismatch);
email.value = "kim@example.com";
console.log(email.checkValidity());

03Objective and prerequisites

Learning objective: Use HTML validation attributes, read the validity state and checkValidity from JavaScript, and style and report invalid fields.

You need: Lesson 62: Input events and form submission

Skills practised: Forms, Native validation.

04Explanation

HTML can describe rules: required, type="email", type="number" with min and max, minlength, maxlength and pattern.

When a form is submitted, the browser checks these rules first. If any fail it shows a message and does not fire submit.

From JavaScript, field.checkValidity() returns true or false, and form.checkValidity() checks every field at once.

field.validity explains the result with flags such as valueMissing, typeMismatch, tooShort, rangeOverflow and patternMismatch.

05Definitions

Constraint validation
The browser's built-in checking of rules such as required, type, min, max and pattern.
checkValidity
A method that returns whether a field or form passes its constraints, firing invalid events for failures.
ValidityState
The object in field.validity with a flag for each kind of failure and a valid summary flag.
pattern attribute
A regular expression the whole value must match.
novalidate
A form attribute that turns off automatic validation on submit.

Open the full glossary

06Visual learning object

Input validation laboratory. Change the attributes and the value of a field and see each validity flag, checkValidity and the :invalid styling update.

Loading the interactive object…

Open the full Input validation laboratory page with its guided experiment.

07Examples

ex-063-01Reading validity flags Browser page (sandboxed preview)

Each rule has its own flag, so you know exactly what is wrong.

const age = document.querySelector("#age");
for (const value of ["", "12", "200", "30"]) {
  age.value = value;
  const v = age.validity;
  console.log(JSON.stringify(value), v.valueMissing, v.rangeUnderflow, v.rangeOverflow, v.valid);
}
Sample input
None
Expected output
"" true false false false "12" false true false false "200" false false true false "30" false false false true
Common mistake
Writing your own range check when min and max already exist.
Try this
Add step="5" and try 31.
Source
examples/ex-063-01-flags.js

ex-063-02Patterns and lengths Browser page (sandboxed preview)

pattern must match the whole value; minlength checks length.

const code = document.querySelector("#code");
for (const value of ["ABC-12", "abc-12", "ABC-123"]) {
  code.value = value;
  console.log(value, code.validity.patternMismatch);
}
const pass = document.querySelector("#pass");
pass.value = "short";
console.log(pass.checkValidity());
Sample input
None
Expected output
ABC-12 false abc-12 true ABC-123 true true
Common mistake
Expecting minlength to fail for a value set from code; length limits are only checked after the person edits the field.
Try this
Make the pattern accept lower case letters too.
Source
examples/ex-063-02-pattern.js

ex-063-03Blocking submission Browser page (sandboxed preview)

If any field is invalid, requestSubmit fires invalid events and no submit.

const form = document.querySelector("#f");
form.addEventListener("submit", (e) => { e.preventDefault(); console.log("submitted"); });
form.addEventListener("invalid", (e) => console.log("invalid:", e.target.name), true);
form.requestSubmit();
form.elements.name.value = "Kim";
form.elements.email.value = "kim@example.com";
console.log(form.checkValidity());
form.requestSubmit();
Sample input
None
Expected output
invalid: name invalid: email true submitted
Common mistake
Listening for invalid on the form without capture: invalid does not bubble.
Try this
Add novalidate and see what changes.
Source
examples/ex-063-03-form-check.js

ex-063-04Styling from validity Browser page (sandboxed preview)

The :invalid pseudo-class follows validity, so CSS can mark fields.

const zip = document.querySelector("#zip");
console.log(zip.matches(":invalid"));
zip.value = "90210";
console.log(zip.matches(":invalid"), zip.matches(":valid"));
Sample input
None
Expected output
true false true
Common mistake
Showing every empty required field as an error before the person has typed anything.
Try this
Use :user-invalid in the CSS panel.
Source
examples/ex-063-04-css-state.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Make the field required

Let the browser enforce a rule.

const form = document.querySelector("#f");
const name = form.elements.name;
console.log(name.checkValidity());

Explain the problem

Map validity flags to messages.

const qty = document.querySelector("#qty");
function problem(field) {
  // TODO: return "Required", "Too small", "Too big" or "OK"
  // using field.validity
}
for (const v of ["", "0", "11", "4"]) {
  qty.value = v;
  console.log(problem(qty));
}

An error summary

Collect every invalid field on submit.

// Write invalidNames(form): returns the names of every invalid control
// (in order). Then set user to "Al", email to "al@example.com",
// age to "9" and log invalidNames(form).join(", ").

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <input id="n" type="number" max="5">
const n = document.getElementById("n");
n.value = "";
console.log(n.checkValidity());
n.value = "9";
console.log(n.checkValidity());

What is printed?

10Debugging investigation

A quantity of 0 is accepted

The order form should refuse a quantity of 0, but the order is placed.

const form = document.getElementById("f");
form.noValidate = true;
let result = "blocked";
form.addEventListener("submit", (event) => {
  event.preventDefault();
  result = "ordered " + form.elements.qty.value;
});
form.requestSubmit();
console.log(result);

More cases in the Debugging Detective Laboratory

11Practical scenario

Checkout forms

Payment pages mark the card fields with required, inputmode and pattern so the browser catches empty or malformed values before any script runs. JavaScript adds friendlier inline messages using the same validity flags, and the server checks everything again.

const rules = ["required", "pattern", "min/max", "type=email"];
console.log("Browser checks:", rules.join(", "));
console.log("Server still validates: true");

12Knowledge check

1. What does the browser do when a required field is empty and the form is submitted?

  • Submits anyway
  • Shows a message and does not fire submit
  • Clears the form
  • Reloads

2. Which flag is true when a type="email" field holds "abc"?

  • valueMissing
  • typeMismatch
  • patternMismatch
  • tooShort

3. An input has pattern="[0-9]{3}" and value "1234". What is validity.patternMismatch?

  • false
  • true
  • undefined
  • It throws

4. Why does this listener never run?

form.addEventListener("invalid", show);
form.checkValidity();
  • invalid does not bubble, so a non-capture listener on the form misses it
  • invalid is not an event
  • checkValidity does not fire events
  • forms cannot listen

5. Why should tests not compare validationMessage text?

  • It is always empty
  • It differs between browsers and languages
  • It is read-only
  • It contains HTML

6. Which approach is best for a sign-up form?

  • Only JavaScript checks
  • HTML constraints plus validity-based messages, and server-side validation
  • Only HTML constraints
  • Only server checks

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Make the field required: Prints false; Valid once filled
  • Explain the problem: Prints each problem; Uses validity
  • An error summary: Prints age; Finds several

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-13-forms-and-validation/lesson-063-native-browser-validation/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • HTML attributes describe validation rules.
  • The browser blocks invalid submissions before submit fires.
  • checkValidity and validity flags expose the result to JavaScript.
  • Client checks help people; the server must still validate.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation native form validation
Context: I am learning native form validation in JavaScript.
Task: Explain required, type, min, max, pattern and the validity API with a small form.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction native form validation drill
Context: I have practised native form validation.
Task: Give me six fields with values and ask which validity flags are true.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging native form validation bug
Context: My invalid listener on the form never runs.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation native form validation practice
Context: I finished the native form validation exercises.
Task: Create three exercises that read validity flags with exact expected output.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review native form validation review
Context: Here is my code that uses native form validation.
Task: Review my form markup and suggest built-in constraints that replace custom code.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.