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

Lesson 64: Custom validation rules

01Opening question

The browser can check that a field is an email address. Can it check that two passwords match, or that a date is in the future?

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

A validator is an ordinary function: it takes a value and returns an error message, or an empty string when the value is fine. It is easy to test without any page.

function checkUsername(value) {
  if (value.length < 3) return "At least 3 characters";
  if (!/^[a-z0-9_]+$/.test(value)) return "Only lower case letters, digits and _";
  return "";
}
for (const v of ["al", "Ada!", "ada_99"]) console.log(JSON.stringify(v), "->", checkUsername(v) || "OK");

03Objective and prerequisites

Learning objective: Write custom validation as pure functions, connect them to fields with setCustomValidity, and validate rules that involve several fields.

You need: Lesson 63: Native browser validation, Lesson 21: Function declarations and expressions

Skills practised: Forms, Custom validation.

04Explanation

Some rules are specific to your app: usernames must be lower case, passwords must match, the end date must be after the start date. You write those yourself.

Write each rule as a validator function that takes a value and returns an error message, or "" when it is valid.

field.setCustomValidity(message) tells the browser the field is invalid with that message. Passing "" marks it valid again.

Run validators on input (for live feedback) and again on submit (to block bad data).

05Definitions

Validator function
A function that takes a value and returns an error message, or an empty string when the value is valid.
setCustomValidity
A method that marks a field invalid with a custom message, or valid again with an empty string.
customError
The validity flag that is true while a custom message is set.
Cross-field validation
Rules that compare two or more fields, such as matching passwords.
Server-side validation
Checking data again on the server, because client checks can be bypassed.

Open the full glossary

06Visual learning object

Input validation laboratory. Write a validator, type values and watch the custom message, customError and the form's overall validity.

Loading the interactive object…

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

07Examples

ex-064-01Connecting a validator to a field Browser page (sandboxed preview)

setCustomValidity turns a message into the field's validity.

const user = document.querySelector("#user");
const checkUser = (v) => /^[a-z]{3,}$/.test(v) ? "" : "Use 3+ lower case letters";
function validate() {
  user.setCustomValidity(checkUser(user.value));
}
user.addEventListener("input", validate);
user.value = "Al";
user.dispatchEvent(new Event("input"));
console.log(user.validity.customError, user.validationMessage);
user.value = "alma";
user.dispatchEvent(new Event("input"));
console.log(user.validity.customError, user.checkValidity());
Sample input
None
Expected output
true Use 3+ lower case letters false true
Common mistake
Forgetting to call setCustomValidity("") once the value is fixed.
Try this
Also reject names that are already taken: ["admin", "root"].
Source
examples/ex-064-01-set-custom.js

ex-064-02Matching passwords Browser page (sandboxed preview)

Re-check the confirmation when either field changes.

const { pw, confirm } = document.querySelector("#f").elements;
function checkMatch() {
  confirm.setCustomValidity(confirm.value === pw.value ? "" : "Passwords do not match");
}
pw.addEventListener("input", checkMatch);
confirm.addEventListener("input", checkMatch);
pw.value = "sunflower7";
confirm.value = "sunflower7";
confirm.dispatchEvent(new Event("input"));
console.log(confirm.validity.valid);
pw.value = "sunflower8";
pw.dispatchEvent(new Event("input"));
console.log(confirm.validity.valid, confirm.validationMessage);
Sample input
None
Expected output
true false Passwords do not match
Common mistake
Only checking when the confirm field changes, so editing the first password leaves a stale result.
Try this
Show the message in a paragraph under the field.
Source
examples/ex-064-02-passwords.js

ex-064-03A table of rules Browser page (sandboxed preview)

Validators in an object make a form's rules easy to read and extend.

const rules = {
  title: (v) => (v.trim() ? "" : "Title is required"),
  end: (v, all) => (v >= all.start ? "" : "End must be on or after the start")
};
function validateForm(form) {
  const all = Object.fromEntries(new FormData(form));
  const errors = {};
  for (const [name, rule] of Object.entries(rules)) {
    const message = rule(all[name], all);
    form.elements[name].setCustomValidity(message);
    if (message) errors[name] = message;
  }
  return errors;
}
const form = document.querySelector("#event");
console.log(JSON.stringify(validateForm(form)));
console.log(form.checkValidity());
Sample input
None
Expected output
{"end":"End must be on or after the start"} false
Common mistake
Comparing dates as Date objects created from mismatched formats; ISO yyyy-mm-dd strings compare correctly as text.
Try this
Add a rule that the start date must be in 2027.
Source
examples/ex-064-03-rule-table.js

ex-064-04Validators are easy to test Browser page (sandboxed preview)

Pure validators need no page to test.

const checkPostcode = (v) => (/^[A-Z]\d[A-Z] ?\d[A-Z]\d$/i.test(v.trim()) ? "" : "Invalid postcode");
const cases = [["M5V 2T6", ""], ["m5v2t6", ""], ["12345", "Invalid postcode"]];
for (const [input, expected] of cases) {
  console.log(input, checkPostcode(input) === expected ? "pass" : "FAIL");
}
Sample input
None
Expected output
M5V 2T6 pass m5v2t6 pass 12345 pass
Common mistake
Mixing validation logic with DOM updates, which makes it hard to test.
Try this
Add a case with a trailing space and decide what it should return.
Source
examples/ex-064-04-pure-tests.js

08Guided exercises

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

The error never clears

Reset setCustomValidity on success.

const nick = document.querySelector("#nick");
function validate() {
  if (nick.value.length < 3) nick.setCustomValidity("Too short");
}
nick.value = "Jo";
validate();
nick.value = "Jojo";
validate();
console.log(nick.checkValidity());

Password rules

Write a pure validator with several rules.

function checkPassword(pw) {
  // TODO: return the first failing message, or "":
  // "At least 10 characters", "Add a number", "Add a capital letter"
}
for (const pw of ["short1A", "longenoughpw", "longenough12", "Longenough12"]) {
  console.log(checkPassword(pw) || "OK");
}

Check a booking

Validate across fields and block submission.

// Write validateBooking(values) -> errors object (pure, no DOM):
//   guests must be 1..6        -> guests: "1 to 6 guests"
//   checkout must be after checkin -> checkout: "Check-out must be after check-in"
// On submit: preventDefault, read values with FormData, set each field's
// custom validity, and log "booked" only when there are no errors,
// otherwise log the error field names joined with ",".

09Prediction

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

// HTML: <input id="x">
const x = document.getElementById("x");
x.setCustomValidity("Nope");
x.value = "anything";
console.log(x.checkValidity());
x.setCustomValidity("");
console.log(x.checkValidity());

What is printed?

10Debugging investigation

Matching passwords still show an error

If the confirm box is typed first and then the password is corrected to match, the form still says the passwords do not match.

const form = document.getElementById("f");
const { pw, confirm } = form.elements;
function checkMatch() {
  confirm.setCustomValidity(confirm.value === pw.value ? "" : "Passwords do not match");
}
confirm.addEventListener("input", checkMatch);
pw.value = "maple";
confirm.value = "maple22";
confirm.dispatchEvent(new Event("input"));
pw.value = "maple22";
pw.dispatchEvent(new Event("input"));
console.log("valid: " + form.checkValidity());

More cases in the Debugging Detective Laboratory

11Practical scenario

Shared validation rules

A booking company writes its validators once as pure functions in a shared module. The browser uses them for instant feedback; the Node.js server imports the same functions to reject bad requests, so the rules can never drift apart.

const validateGuests = (n) => (n >= 1 && n <= 6 ? "" : "1 to 6 guests");
console.log("browser:", validateGuests(3) || "OK");
console.log("server:", validateGuests(9) || "OK");

12Knowledge check

1. What should a validator function return when the value is valid?

  • true
  • An empty string
  • null always
  • The value

2. What does setCustomValidity("") do?

  • Marks the field invalid
  • Clears the custom error so the field can be valid
  • Empties the field
  • Removes the field

3. Why does the field stay invalid after the person fixes it?

if (v.length < 3) field.setCustomValidity("Too short");
  • The custom error is never cleared
  • length is wrong
  • setCustomValidity needs two arguments
  • input events do not fire

4. Why re-check "confirm password" when the first password changes?

  • It is required by HTML
  • The match depends on both fields
  • To clear the first field
  • It is not needed

5. A validator returns "" for valid. What does checkName("Ada") || "OK" give when Ada is valid?

  • ""
  • "OK"
  • true
  • undefined

6. Where should validation run for a payment form?

  • Only in the browser
  • In the browser for feedback and on the server for safety
  • Only on the server
  • Nowhere

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.

  • The error never clears: Prints true; Short values are still invalid
  • Password rules: Prints each result; Returns empty string when valid
  • Check a booking: Reports checkout; Pure validator: valid booking; Pure validator: too many guests

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-064-custom-validation-rules/. 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

  • Write app-specific rules as pure validator functions.
  • setCustomValidity connects a message to a field; clear it with "".
  • Re-check cross-field rules when any related field changes.
  • Validate again on the server.

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 custom form validation
Context: I am learning custom form validation in JavaScript.
Task: Explain validator functions, setCustomValidity and cross-field rules 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 custom form validation drill
Context: I have practised custom form validation.
Task: Give me six validator functions with inputs and ask what each returns.
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 custom form validation bug
Context: My field stays invalid even after I correct the value.
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 custom form validation practice
Context: I finished the custom form validation exercises.
Task: Create three custom validation exercises, including one cross-field rule.
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 custom form validation review
Context: Here is my code that uses custom form validation.
Task: Review my validation code for impure validators and errors that never clear.
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.