../courses.php
RegEx
REGEX109
3
Validate Text Patterns
Validation patterns check whether input follows an expected shape.
What does validation mean in RegEx?
Validation means checking whether the whole input matches the expected pattern, not just whether part of it matches.
Validation is stricter than searching.
A search may find a pattern anywhere inside text.
Validation usually needs the whole value to match.
That is why anchors are common in validation patterns.
Good validation patterns are clear, tested, and not more clever than needed.
Validating a simple code
const pattern = /^[A-Z]{3}-[0-9]{4}$/;
console.log(pattern.test("ABC-1234")); // true
console.log(pattern.test("abc-1234")); // false
console.log(pattern.test("ABC-123")); // false
console.log(pattern.test("XXABC-1234YY")); // false
^ starts the whole-value check.
[A-Z]{3} requires three uppercase letters.
- requires a dash.
[0-9]{4} requires four digits.
$ ends the whole-value check.
Forms
Validation helps reject badly shaped input.
Codes
Part numbers and IDs often have predictable shapes.
Safety
Anchors stop partial matches from passing.
Clarity
A simple readable pattern is easier to maintain.
Partial validation
Whole-value validation
Ask ChatGPT: "Does this validation RegEx require the whole input to match, and what good and bad examples should I test?"
Create a pattern for three uppercase letters, a dash, and four digits.
Test a valid value.
Test a lowercase value.
Test a value with too few digits.
Explain why anchors matter in validation.
Letting partial matches pass validation.
Making the pattern too clever to read.
Testing only successful input.
Forgetting that uppercase and lowercase can matter.
Using RegEx for validation that should be handled by other code too.
Build simple validation patterns that check the whole input shape.
Login - Jit4All
Login
Welcome back to Jit4All