I would like to divide the error messages according to the validation patterns,for example, in below, there are 2 patterns
Validators.pattern(/[^ +]/),
Validators.pattern(/^[ +|a-zA-Z0-9]+$/),
but only one message can be set.
<md-error *ngIf="locaCd.errors?.pattern">
onny blank is unacceptable AND must be filled by a~z,A~Z or number.
</md-error>
Is there anyway to divide into each witout making CustomValidation??
Angular uses directives to match these attributes with validator functions in the framework. Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors that results in an INVALID status, or null, which results in a VALID status.
ng-dirty: The ng-dirty class tells that the form has been made dirty (modified ) by the user. It returns true if the user has modified the form. Return type: Return Boolean True if the form/input field is modified by the user else it returns False.
Validations errors are errors when users do not respond to mandatory questions. A validation error occurs when you have validation/response checking turned on for one of the questions and the respondent fails to answer the question correctly (for numeric formatting , required response).
By default Validators.pattern()
accepts parameter as pattern: string | RegExp
so i will better suggest you to create you custom validation which handle a single method can handle dynamically for you.
For example demo.component.ts
import { FormGroup, FormControl, Validators, ValidatorFn } from '@angular/forms';
this.form = new FormGroup({
email: new FormControl('', [
this.customPatternValid({ pattern: /[A-Z]/, msg: 'Small characters not allowed' }),
this.customPatternValid({ pattern: /^([^0-9]*)$/, msg: 'Numbers is not allowed' })
]),
password: new FormControl('', [
Validators.required
])
});
// Create our customPatternValid function
public customPatternValid(config: any): ValidatorFn {
return (control: FormControl) => {
let urlRegEx: RegExp = config.pattern;
if (control.value && !control.value.match(urlRegEx)) {
return {
invalidMsg: config.msg
};
} else {
return null;
}
};
}
For example demo.component.html
<form [formGroup]="form">
<input type="email" placeholder="Email" formControlName="email"/>
<div *ngIf="!form.controls.email.valid && (form.controls.email.dirty ||form.controls.email.touched)" class="error">
<div *ngIf="form.controls.email.errors.invalidMsg">
{{form.controls.email.errors.invalidMsg}}
</div>
</div>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With