📖 Scenario: You are building a user registration form in Angular. You want to ensure that the username entered by the user does not contain any spaces.
🎯 Goal: Build a custom validator function called noSpaceValidator that checks if the username contains spaces and use it in an Angular reactive form control.
📋 What You'll Learn
Create a custom validator function named noSpaceValidator
The validator should return { 'noSpace': true } if the value contains spaces
Use the noSpaceValidator in a reactive form control named username
Initialize the form group with the username control using Angular's FormBuilder
💡 Why This Matters
🌍 Real World
Custom validators are used in real-world Angular apps to enforce specific input rules beyond built-in validators, such as checking for spaces, special characters, or custom formats.
💼 Career
Knowing how to write and apply custom validators is essential for Angular developers to build robust forms that meet business rules and improve user input quality.
Progress0 / 4 steps
1
Set up the reactive form with a username control
Import FormBuilder and FormGroup from @angular/forms. Create a form group called form with a control named username initialized to an empty string.
Angular
Hint
Use this.fb.group to create the form group and initialize username with an empty string.
2
Create the custom validator function noSpaceValidator
Write a function named noSpaceValidator that takes a FormControl as input and returns { noSpace: true } if the control's value contains any spaces, otherwise returns null.
Angular
Hint
Check if control.value contains a space using indexOf(' '). Return the error object if true, else null.
3
Add the noSpaceValidator to the username control
Modify the username control in the form group to include the noSpaceValidator as a validator.
Angular
Hint
Pass noSpaceValidator as the second element in the array for the username control.
4
Complete the Angular component with the form and validator
Ensure the Angular component class includes the form property, the constructor with FormBuilder injection, the noSpaceValidator function, and the username control uses the validator. This completes the reactive form setup with the custom validator.
Angular
Hint
Wrap the form and validator inside an Angular component class with proper imports and decorator.
Practice
(1/5)
1. What does a custom validator function in Angular return when the input is valid?
The regex /^[a-zA-Z]+$/ matches only letters. 'abc123' contains digits, so test returns false.
Step 2: Determine validator return value
Since test is false, the validator returns the error object { alphaOnly: true } indicating invalid input.
Final Answer:
{ alphaOnly: true } -> Option A
Quick Check:
Input with digits fails alphaOnly validator [OK]
Hint: Regex test false means return error object, not null [OK]
Common Mistakes:
Assuming digits pass the regex
Confusing true/false return values
Expecting null for invalid input
4. Identify the error in this custom validator code snippet:
function minLengthFive(control: AbstractControl) {
if (control.value.length < 5) {
return { minLengthFive: true };
}
}
medium
A. Incorrect error object key name
B. Missing return null for valid input
C. Using control.value.length without checking null
D. Validator should return boolean instead of object
Solution
Step 1: Check for runtime errors
The code accesses control.value.length without checking if control.value is null or undefined, causing TypeError when value is null (common for new FormControls).
Step 2: Angular validator best practice
Always check if (control.value == null) return null; before accessing properties like length. Explicit return null; for valid cases is also recommended.
Final Answer:
Using control.value.length without checking null -> Option C
Quick Check:
control.value can be null causing crash [OK]
Hint: Always check control.value != null before .length [OK]
Common Mistakes:
Not checking control.value for null before .length
Returning undefined instead of null for valid input
Confusing error object keys with validator names
5. You want to create a custom validator that checks if a password contains at least one uppercase letter, one lowercase letter, and one digit. Which of these validator implementations correctly applies this logic?
B. function passwordValidator(control: AbstractControl) {
if (!control.value.match(/[A-Z]/) || !control.value.match(/[a-z]/) || !control.value.match(/[0-9]/)) {
return null;
}
return { passwordStrength: true };
}
C. function passwordValidator(control: AbstractControl) {
const val = control.value;
if (val.length < 8) return { passwordStrength: true };
return null;
}
D. function passwordValidator(control: AbstractControl) {
const val = control.value;
if (val.includes(' ')) return { passwordStrength: true };
return null;
}
Solution
Step 1: Understand password requirements
The password must have at least one uppercase, one lowercase, and one digit character.
Step 2: Analyze each option's logic
function passwordValidator(control: AbstractControl) {
const val = control.value || '';
const hasUpper = /[A-Z]/.test(val);
const hasLower = /[a-z]/.test(val);
const hasDigit = /\d/.test(val);
return hasUpper && hasLower && hasDigit ? null : { passwordStrength: true };
} correctly tests all three conditions and returns null if all pass, error object otherwise. function passwordValidator(control: AbstractControl) {
if (!control.value.match(/[A-Z]/) || !control.value.match(/[a-z]/) || !control.value.match(/[0-9]/)) {
return null;
}
return { passwordStrength: true };
} reverses logic, returning null on failure. The remaining options check unrelated conditions.