Back to blog

JavaScript Regex Validator: Test and Validate Patterns

Build a JavaScript regex validator

A JavaScript regex validator checks whether input follows a defined text pattern. Common uses include UUIDs, slugs, dates, email-like strings, and identifiers. Start with clear requirements and test both accepted and rejected values.

Use the DevToolkit Regex Tester to experiment with patterns, flags, matches, and replacements in your browser.

Example: validate a slug

const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

slugPattern.test("json-to-xml"); // true
slugPattern.test("JSON to XML"); // false

The anchors require the entire string to match. The non-capturing group allows additional hyphen-separated words without accepting leading, trailing, or repeated hyphens.

Example: validate a UUID v4

const uuidV4Pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

function isUuidV4(value) {
  return uuidV4Pattern.test(value);
}

This verifies the canonical format, version marker, and variant marker. It does not prove that the value is unique or secure. See the complete UUID regex pattern guide.

Use flags deliberately

  • i ignores letter case.
  • g finds all matches instead of stopping at the first.
  • m changes how ^ and $ behave across lines.
  • u enables Unicode-aware matching behavior.

Only add flags that match the requirement. For example, g is usually unnecessary when a validator only needs a boolean result.

Test valid and invalid values

For every validator, include examples for:

  • A normal valid value.
  • An empty string.
  • Extra whitespace.
  • A value with an unexpected character.
  • A value just below and above the allowed length.
  • Uppercase and Unicode input when relevant.

Regex checks should be paired with server-side validation. Client-side checks improve feedback, but users can bypass browser code.

Avoid common regex problems

Do not use .* as a shortcut when the input has a defined structure. Escape literal punctuation such as . and ?, anchor full-string validation, and avoid nested overlapping quantifiers that can cause excessive backtracking.

For more patterns, read the regex cheat sheet and test the final expression with the online Regex Tester.

Summary

A good JavaScript regex validator has explicit requirements, full-string anchors when needed, targeted flags, and tests for edge cases. Use regex for input shape, then enforce business rules and security on the server.