You want to accept a username that only contains letters, numbers, and underscores. Which PHP code correctly validates this input using filter_var() and a custom pattern?
hard📝 Application Q15 of 15
PHP - Superglobals and Web Context
You want to accept a username that only contains letters, numbers, and underscores. Which PHP code correctly validates this input using filter_var() and a custom pattern?
The username must only have letters, numbers, and underscores, so a regular expression is needed to check this pattern.
Step 2: Use FILTER_VALIDATE_REGEXP with correct pattern
FILTER_VALIDATE_REGEXP allows validating input against a regex pattern. The pattern '/^[a-zA-Z0-9_]+$/' matches only allowed characters.
Step 3: Eliminate distractors
The incorrect options use filters for integer validation, string sanitization, or email validation, none of which enforce the specific pattern of letters, numbers, and underscores.
Final Answer:
Code using FILTER_VALIDATE_REGEXP with pattern '/^[a-zA-Z0-9_]+$/' -> Option A
Quick Check:
Validate username with FILTER_VALIDATE_REGEXP + regex [OK]
Quick Trick:Use FILTER_VALIDATE_REGEXP with regex for custom pattern validation [OK]
Common Mistakes:
Using sanitize instead of validate
Using email or int filters for username
Not using regex for pattern matching
Master "Superglobals and Web Context" in PHP
9 interactive learning modes - each teaches the same concept differently