Reputation: 1973
I have a component ValidationMessage that I use for displaying a validating message. ValidationMessage is used in VendorComonent; also, I have a validationmessage_vendor ts file with the messages that will be displayed in a div
My problem is that it works fine for any validation like required or minlength, but doesn't work for the pattern that I am using
How to write this type: 'pattern(\'^[0-9]{7}$\')'
in validationmessage_vm.ts file in order to work?
.ts method that involves the form
initForm() {
this.activateVendorForm = this.fb.group({
vendorNumber: ['', [Validators.required, Validators.pattern('^[0-9]{7}$'), Validators.maxLength(7), Validators.minLength(7)]]
})
}
validationmessage_vm.ts
const merchant_dashboard_vm = {
'vendorNumber': [
{ type: 'required', message: 'Vendor Number is required'},
{ type: 'pattern(\'^[0-9]{7}$\')', message: 'Vendor Number should have 7 numbers'},
],
};
export default merchant_dashboard_vm;
validationmessage.component.ts
export class ValidationMessageComponent implements OnInit {
@Input() vm: string = '';
@Input() control: any = null;
@Input() controlName: string = '';
validationMessages = null;
ngOnInit() {
if(this.vm == 'merchant_dashboard_vm') this.validationMessages = merchant_dashboard_vm;
}
}
validationmessage.component.html
<div class="from-group" *ngFor="let vm of validationMessages[controlName]">
<div class="alert alert-danger" *ngIf="control.hasError(vm.type)">
{{vm.message}}
</div>
</div>
Upvotes: 0
Views: 119
Reputation: 1454
The pattern inside the validators should be covered with the forward
and backward
slash instead of double-quotes.
Validators.pattern(/^[0-9]{7}$/)
Hope this helps!
initForm() {
this.activateVendorForm = this.fb.group({
vendorNumber: ['', [Validators.required, Validators.pattern(/^[0-9]{7}$/), Validators.maxLength(7), Validators.minLength(7)]]
})
}
Upvotes: 1