Validators help check if the user typed the right kind of information in a form. They make sure the form is filled out correctly before sending it.
Validators (required, minLength, pattern) in Angular
import { Validators } from '@angular/forms'; this.myForm = new FormGroup({ name: new FormControl('', [Validators.required, Validators.minLength(3), Validators.pattern('^[a-zA-Z]+$')]) });
Validators.required checks if the field is not empty.
Validators.minLength(n) checks if the input has at least n characters.
Validators.pattern(regex) checks if the input matches the given regular expression.
new FormControl('', Validators.required)
new FormControl('', Validators.minLength(5))
new FormControl('', Validators.pattern('^[0-9]+$'))
new FormControl('', [Validators.required, Validators.minLength(4), Validators.pattern('^[a-z]+$')])
This Angular component creates a simple form with one input for username. It uses three validators: required, minLength(3), and pattern to allow only letters. It shows error messages below the input if the user input is invalid. The submit button is disabled until the form is valid.
import { Component } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-simple-form', template: ` <form [formGroup]="userForm" (ngSubmit)="submit()"> <label for="username">Username:</label> <input id="username" formControlName="username" aria-describedby="usernameHelp" /> <div id="usernameHelp" *ngIf="username.invalid && (username.dirty || username.touched)" style="color: red;"> <div *ngIf="username.errors?.required">Username is required.</div> <div *ngIf="username.errors?.minlength">Username must be at least 3 characters.</div> <div *ngIf="username.errors?.pattern">Username must contain only letters.</div> </div> <button type="submit" [disabled]="userForm.invalid">Submit</button> </form> ` }) export class SimpleFormComponent { userForm = new FormGroup({ username: new FormControl('', [ Validators.required, Validators.minLength(3), Validators.pattern('^[a-zA-Z]+$') ]) }); get username() { return this.userForm.get('username')!; } submit() { if (this.userForm.valid) { alert('Form submitted with username: ' + this.username.value); } } }
Use Validators.compose to combine multiple validators if needed, but passing an array works well.
Angular runs validators automatically when the user types or changes the input.
Always provide user-friendly error messages to help fix mistakes.
Validators check user input to keep forms correct and complete.
Use required, minLength, and pattern to cover common validation needs.
Show clear error messages and disable submit until the form is valid.
Practice
Solution
Step 1: Understand the purpose of
This validator checks if the input field has any value and marks it invalid if empty.Validators.requiredStep 2: Compare with other validators
minLengthchecks length,patternchecks format, andmaxLengthlimits length, but none enforce non-empty input.Final Answer:
Validators.required -> Option CQuick Check:
Non-empty input = Validators.required [OK]
- Confusing required with minLength
- Using pattern to check empty input
- Thinking maxLength enforces presence
Solution
Step 1: Recall Angular validator syntax
Validators likeminLengthare functions called with the required parameter in parentheses.Step 2: Identify correct function call
Validators.minLength(5)correctly calls the function with 5 as argument; other options use invalid syntax.Final Answer:
Validators.minLength(5) -> Option AQuick Check:
Function call with parentheses = Validators.minLength(5) [OK]
- Using assignment (=) instead of function call
- Using colon (:) instead of parentheses
- Using brackets [] incorrectly
new FormControl('', [Validators.required, Validators.minLength(3)])What will be the validation status if the user enters 'Hi'?
Solution
Step 1: Check input against Validators.required
The input 'Hi' is not empty, so the required validator passes.Step 2: Check input length against Validators.minLength(3)
'Hi' has length 2, which is less than 3, so minLength validator fails.Final Answer:
Invalid because input length is less than 3 -> Option DQuick Check:
Length 2 < 3 = Invalid minLength [OK]
- Assuming 'Hi' is valid because not empty
- Ignoring minLength validator
- Confusing pattern validator presence
new FormControl('', [Validators.required, Validators.pattern('[a-zA-Z]+'))Solution
Step 1: Check syntax of Validators.pattern
The pattern validator call has an opening parenthesis but is missing the closing parenthesis at the end.Step 2: Verify other options
Pattern can accept a string, and required can be combined with pattern, so options B and C are incorrect.Final Answer:
Missing closing parenthesis for Validators.pattern -> Option AQuick Check:
Unmatched parentheses cause syntax error [OK]
- Forgetting closing parenthesis
- Thinking pattern needs RegExp object only
- Believing required and pattern can't combine
Solution
Step 1: Check required presence
The input must not be empty, soValidators.requiredis needed.Step 2: Check length and pattern validators
Validators.minLength(4)ensures at least 4 characters, andValidators.pattern('^[0-9]+$')ensures only digits.Step 3: Evaluate other options
[Validators.required, Validators.minLength(4), Validators.pattern('[a-zA-Z]+')] uses letters pattern, [Validators.minLength(4), Validators.pattern('^[0-9]+$')] misses required, [Validators.required, Validators.pattern('^[0-9]+$')] misses minLength(4).Final Answer:
[Validators.required, Validators.minLength(4), Validators.pattern('^[0-9]+$')] -> Option BQuick Check:
Required + minLength + digit pattern = [Validators.required, Validators.minLength(4), Validators.pattern('^[0-9]+$')] [OK]
- Using letter pattern instead of digit pattern
- Omitting required validator
- Relying only on pattern for length
Ready to prove it?
Pass the test and this pattern moves unknown
