Bird
Raised Fist0
Angularframework~20 mins

Custom validators in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Validator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
1:30remaining
What happens when a custom validator returns null?
In Angular, a custom validator function returns null. What does this mean for the form control's validity?
Angular
function myValidator(control: AbstractControl): ValidationErrors | null {
  return null;
}
AThe control is valid because null means no errors.
BThe control is invalid because null means an error occurred.
CThe control's value is reset to empty.
DThe validator is ignored and does not run.
Attempts:
2 left
💡 Hint
Think about what Angular expects from a validator when there are no problems.
📝 Syntax
intermediate
2:00remaining
Identify the correct custom validator syntax
Which of the following is the correct way to write a synchronous custom validator function in Angular?
Afunction myValidator(control: AbstractControl): boolean { return control.value.length > 3; }
Bfunction myValidator(control: AbstractControl) { if (control.value.length > 3) return null; else return { tooShort: true }; }
Cfunction myValidator(control: AbstractControl): ValidationErrors | null { return control.value.length > 3 ? null : { tooShort: true }; }
Dfunction myValidator(control: AbstractControl): string | null { return control.value.length > 3 ? 'valid' : null; }
Attempts:
2 left
💡 Hint
Check the return type and syntax carefully.
❓ state_output
advanced
2:00remaining
What is the validation state after applying this custom validator?
Given this custom validator and a form control with value 'abc', what is the control's errors property after validation?
Angular
function startsWithAValidator(control: AbstractControl): ValidationErrors | null {
  return control.value.startsWith('A') ? null : { startsWithA: true };
}

const control = new FormControl('abc', startsWithAValidator);
const errors = control.errors;
Anull
B{ startsWithA: true }
C{ required: true }
Dundefined
Attempts:
2 left
💡 Hint
Check if the string 'abc' starts with 'A'.
🔧 Debug
advanced
2:30remaining
Why does this custom validator cause a runtime error?
This custom validator throws an error when the form control value is empty. Why?
Angular
function positiveNumberValidator(control: AbstractControl): ValidationErrors | null {
  if (control.value == null || control.value <= 0) {
    return { notPositive: true };
  }
  return null;
}
ABecause the validator must return a Promise, not null or object.
BBecause the validator must check control.valid instead of control.value.
CBecause the function is missing a return statement.
DBecause control.value can be null or undefined, and comparing with <= causes an error.
Attempts:
2 left
💡 Hint
Think about what happens if control.value is empty or missing.
🧠 Conceptual
expert
3:00remaining
How to create a reusable parameterized custom validator?
You want to create a custom validator that checks if a control's value length is at least a minimum number, passed as a parameter. Which approach correctly creates this reusable validator?
A
function minLengthValidator(min: number): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null =&gt; {
    return control.value.length &gt;= min ? null : { minLength: { requiredLength: min, actualLength: control.value.length } };
  };
}
B
function minLengthValidator(control: AbstractControl, min: number): ValidationErrors | null {
  return control.value.length &gt;= min ? null : { minLength: { requiredLength: min, actualLength: control.value.length } };
}
C
const minLengthValidator = (min: number, control: AbstractControl): ValidationErrors | null =&gt; {
  return control.value.length &gt;= min ? null : { minLength: { requiredLength: min, actualLength: control.value.length } };
};
D
function minLengthValidator(min: number): ValidationErrors {
  if (control.value.length &lt; min) {
    return { minLength: true };
  }
  return null;
}
Attempts:
2 left
💡 Hint
Remember Angular expects a function returning a validator function for parameterized validators.

Practice

(1/5)
1. What does a custom validator function in Angular return when the input is valid?
easy
A. an empty string
B. true
C. false
D. null

Solution

  1. Step 1: Understand Angular validator return values

    Angular custom validators return null when the input passes validation, meaning no errors.
  2. Step 2: Identify the valid return for no errors

    Returning null signals the form control is valid, while any object means invalid.
  3. Final Answer:

    null -> Option D
  4. Quick Check:

    Valid input returns null [OK]
Hint: Valid inputs always return null from validators [OK]
Common Mistakes:
  • Returning true or false instead of null or error object
  • Returning empty string instead of null
  • Confusing valid with invalid return values
2. Which of the following is the correct signature for a synchronous custom validator function in Angular?
easy
A. function myValidator(event: Event): string
B. function myValidator(control: AbstractControl): ValidationErrors | null
C. function myValidator(control: FormGroup): void
D. function myValidator(value: string): boolean

Solution

  1. Step 1: Recall Angular validator function signature

    A synchronous custom validator takes an AbstractControl and returns ValidationErrors or null.
  2. Step 2: Match the correct function signature

    function myValidator(control: AbstractControl): ValidationErrors | null matches the required signature exactly, others do not fit Angular patterns.
  3. Final Answer:

    function myValidator(control: AbstractControl): ValidationErrors | null -> Option B
  4. Quick Check:

    Validator signature = function myValidator(control: AbstractControl): ValidationErrors | null [OK]
Hint: Validator functions take AbstractControl and return errors or null [OK]
Common Mistakes:
  • Using wrong parameter types like string or Event
  • Returning boolean instead of error object or null
  • Missing return type or returning void
3. Given this custom validator code, what will be the validation result for input value 'abc123'?
function alphaOnly(control: AbstractControl) {
  const valid = /^[a-zA-Z]+$/.test(control.value);
  return valid ? null : { alphaOnly: true };
}
medium
A. { alphaOnly: true }
B. true
C. null
D. false

Solution

  1. Step 1: Analyze the regex test on input 'abc123'

    The regex /^[a-zA-Z]+$/ matches only letters. 'abc123' contains digits, so test returns false.
  2. Step 2: Determine validator return value

    Since test is false, the validator returns the error object { alphaOnly: true } indicating invalid input.
  3. Final Answer:

    { alphaOnly: true } -> Option A
  4. 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

  1. 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).
  2. 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.
  3. Final Answer:

    Using control.value.length without checking null -> Option C
  4. 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?
hard
A. 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 }; }
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

  1. Step 1: Understand password requirements

    The password must have at least one uppercase, one lowercase, and one digit character.
  2. 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.
  3. Final Answer:

    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 }; } -> Option A
  4. Quick Check:

    All conditions true returns null, else error [OK]
Hint: Return null only if all conditions are met, else error [OK]
Common Mistakes:
  • Returning null on invalid input
  • Checking only length or spaces, not required chars
  • Mixing up logic conditions in if statements
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard