Skip to content
Tutorials Center
My learning

Topics

Lesson 153 of 156 ยท Practice and Review

Validating Emails, Usernames, Passwords, URLs and Numbers

Practical JavaScript validation recipes - email, username, password strength, URLs with the URL constructor, numbers, ranges and the Constraint Validation API.

Almost every app checks user input: a sign-up form, a search box, a settings page. The checks look similar from project to project, so it pays to keep a small toolkit of tested validators instead of inventing a new regular expression every time.

This lesson is a set of recipes. For each kind of value you will see what a good check looks like, where it stops being reliable, and a function you can copy into your own code. You should already know the basics of regular expressions and form handling.

Validation in the browser is for the user's convenience, not for security. Anyone can bypass your JavaScript. Always validate again on the server, and never trust a value just because the page checked it.

A shape for every validator

A validator that only returns true or false is hard to use: the form cannot tell the user what is wrong. A friendlier shape is to return an error message, or null when the value is fine:

JavaScript
function validateSomething(value) {
  if (/* problem */ false) return "Explain the problem in plain words.";
  return null; // valid
}

All the recipes below follow that shape. Each one also trims or normalizes the input first when that makes sense, because users paste values with stray spaces.

Emails

A full email validator is practically impossible, because the real rules (RFC 5322) allow strange but legal addresses such as "john smith"@example.com. What you actually want is a sanity check: it catches typos like a missing @ and lets everything plausible through. The only real proof that an address works is sending a confirmation message.

JS Email sanity check

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In an HTML form, <input type="email"> already applies a similar rule for you. See Input types.

Usernames

Usernames usually follow a few simple rules: a length range, a limited alphabet and a sensible first character. Writing each rule separately gives better messages than one big pattern.

JS Username rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the case-insensitive reserved check: "Admin" and "admin" must both be refused, or people will impersonate staff with a capital letter.

Passwords and strength levels

Modern guidance (for example from NIST) favors length over complexity. A long passphrase beats P@ssw0rd!, and forcing a symbol often makes people choose predictable passwords. A strength meter should therefore reward length first, then variety, and penalize obviously bad choices.

JS A simple strength score

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Keep two ideas apart. validatePassword is a rule: the form refuses the value. passwordStrength is feedback: it only advises. Never store or log the password itself in client-side code, and let the user paste into the field (blocking paste breaks password managers).

URLs

Do not write a regular expression for URLs. The built-in URL constructor already contains a real parser: it throws on invalid input and splits valid ones into parts.

JS Validating URLs with new URL()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The protocol check matters. new URL("javascript:alert(1)") is a perfectly valid URL, and putting it in an href creates a script-injection hole. Allow-list the protocols you accept. See URL and History and XSS and safe DOM updates.

Numbers, integers and ranges

Form fields give you strings, so numeric validation starts with conversion. Number("") is 0 and Number(" ") is 0 too, so reject empty input first. parseFloat("12abc") quietly returns 12, so for strict checks prefer Number() and test the result with Number.isFinite.

JS Numeric validators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two details worth remembering: -3 % 2 is -1 in JavaScript, so a naive n % 2 === 1 fails for negative odd numbers (the code above uses Math.abs). And "1e3" converts to 1000, so if your field should only contain digits, add a pattern check such as /^-?\d+(\.\d+)?$/ before converting.

Regex pitfalls to avoid

  • Forgetting anchors. /\d{5}/ matches inside "abc123456xyz". Use ^ and $ to demand that the whole string matches.
  • A global flag on a reused regex. A regex with the g flag remembers lastIndex, so calling .test() twice on the same object alternates between true and false. Do not use g for validation.
  • Catastrophic backtracking. A pattern like /^(a+)+$/ can take exponential time on a long non-matching input such as "aaaaaaaaaaaaaaaaaaaaaaaa!". Avoid nested quantifiers, and cap the input length before testing.
  • Over-clever patterns. A 300-character email regex fails valid addresses and nobody can maintain it. Prefer simple rules plus a confirmation step.
JS The sticky g flag

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Letting the browser help: the Constraint Validation API

HTML attributes such as required, minlength, pattern and type="email" give you validation for free, and setCustomValidity() lets your own function feed its message into the same system. That way you reuse the browser's error bubbles and the :invalid CSS state.

Custom rules with setCustomValidity

Remember to call setCustomValidity("") when the value becomes valid, otherwise the field stays invalid forever.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a simple /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/ check usually enough for email addresses on a form?

    A full validator is impractical. A sanity check catches mistakes, and sending a confirmation message verifies ownership.
  2. 2. What is the best way to check whether a string is a valid web URL?

    The URL constructor is a real parser. The protocol check blocks values such as javascript: that parse fine but are dangerous in links.
  3. 3. What does validateNumber("") need special handling for, if it uses Number()?

    An empty or whitespace-only string converts to 0, so check for an empty string before converting.
  4. 4. Why should you not use the g flag on a regular expression you reuse for validation?

    With g (or y), test() continues from lastIndex, which makes the same input pass and then fail.
  5. 5. What is -3 % 2 in JavaScript?

    The remainder takes the sign of the dividend, so a check like n % 2 === 1 misses negative odd numbers.

Summary

  • Return an error message (or null) from each validator so the UI can explain the problem.
  • Emails: use a simple sanity regex and confirm by sending a message. Usernames: check length, alphabet and first character as separate rules.
  • Passwords: reward length first, give strength as advice, and never block pasting.
  • URLs: parse with new URL() and allow-list the protocol.
  • Numbers: reject empty strings, use Number() plus Number.isFinite, and watch the sign of %.
  • Anchor your patterns, avoid the g flag and nested quantifiers, and always validate again on the server.
  • setCustomValidity() lets your own rules use the browser's validation UI.

Next: Interview Questions โ€” test what you have learned against common questions.