How to implement a custom validator which is applied only when the form control is valid?
Something like this would be ideal:
static isValid(control: FormControl) {
if (control.valid) {
// custom validation checks here
return {isNotValid: true};
}
return null;
}
but here control.valid is always true, so it will be applied even if other will invalidate the field.
Is there a way to achieve this?
Detailed example
Source code here: https://stackblitz.com/edit/angular-conditional-validator
app.component.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MyValidator } from './validators.service';
@Component({
selector: 'my-app',
template: `
<form>
<label>Name:</label>
<input [formControl]="form.get('name')">
</form>
`
})
export class AppComponent {
form = new FormGroup ({
name: new FormControl('', [
MyValidator.isValidString,
MyValidator.isValidName,
])
});
}
validators.service.ts
import { FormControl } from '@angular/forms';
export class MyValidator {
static isValidString(control: FormControl) {
if (!control.value || typeof control.value !== 'string') {
return {isNotValidString: true};
}
return null;
}
static isValidName(control: FormControl) {
if (control.valid && control.value !== 'John Doe') {
return {isNotValidName: true};
}
return null;
}
}
How to make that isValidName validator is applied/executed only when control is valid, i.e. the previous validators returned null?
Cause right now, I believe angular will first run all sync validators, then will run all async validators, and only after will set the control status, which is the correct approach I think.
Note
This example is for demonstration only, it has no real live application.
control.validis always valid ? edit your question to add a minimum verifiable example. - HDJEMAI