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.
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).
Keep validators pure (no DOM access) so you can unit test them, and reuse them on the server in Node.js.
setCustomValidity sticks until you clear it. Always call it on every check, with "" for success, or the field stays invalid forever.
Cross-field rules (confirm password, date ranges) belong to the form, not one field. Re-check the dependent field whenever either value changes.
Never trust client validation alone: requests can be made without your form. The server must apply the same rules.
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.
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.
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.
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
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.
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 explanationcustom 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 predictioncustom 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.
Debuggingcustom 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 generationcustom 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 reviewcustom 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.