0Pricing
JavaScript Academy · Lesson

Validation & small pitfalls

Validate whole strings with anchors, avoid greedy overmatch, use word boundaries, add simple extra checks, and beware /g with test().

Whole-string validation

Goal: Validate safely without surprises.

  • Use ^ and $ to match the whole string
  • Avoid greedy overmatch; use lazy *? when needed
  • Use \\b word boundaries
  • Beware /g with test()
Validation & small pitfalls — illustration 1

Anchors in practice

Add ^ and $ so partial matches do not slip through.

// Validate 4–6 digits ONLY (no spaces, no letters)
function isPin(text) {
  const re = /^\\d{4,6}$/;
  return re.test(text);
}

console.log("1234 ->", isPin("1234"));
console.log("12 34 ->", isPin("12 34"));
console.log("a123 ->", isPin("a123"));
Validation & small pitfalls — illustration 2

All lessons in this course

  1. Regex basics — literals, test, anchors, and flags
  2. Groups, Captures, and Replace
  3. Validation & small pitfalls
← Back to JavaScript Academy