I have an angular reactive form with default Validation.required
and a CustomValidation
.
Inside the CustomValidation
I intended to check if the control is touched, but somehow this is not working.
import {
CustomValidation
} from './CustomValidator';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
customForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.customForm = this.fb.group({
customInput: [
'', [Validators.required, CustomValidation.customEmailValidation()],
],
});
}
}
// CustomValidation.ts
import {
AbstractControl,
ValidationErrors,
ValidatorFn
} from '@angular/forms';
export class CustomValidation {
static customEmailValidation(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.touched && control.value.length === 0) {
console.log(control);
return {
customError: {
hasError: true,
errorType: 'empty field', // this can be any name
errorLabel: 'test',
},
};
}
return null;
};
}
}
<form [formGroup]="customForm">
<input formControlName="customInput" />
<button [disabled]="this.customForm.invalid">Submit</button>
</form>
I am expecting that the console.log inside the static method customEmailValidation
will log the control object when the field will be touched. By touch I mean, I only click on the input.But that is not happening.
I also tried using updateOn
customInput: ['', {validators:[CustomValidation.customEmailValidation(),Validators.required],updateOn:"blur"}]
Please help me in understanding why it is not working.