I'm trying to use md-error in angular material to validate user inputs from client side.
So in my case I'm trying to validate an input field that accept two types of patterns.
Regular Expression 1 : Accept first 9 characters as numbers then 10th
character as x or X or v or V
Regular Expression 2 : Accept 12 characters as numbers
So I implemented that in my typescript file like following
samplefile.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
const NIC_REGEX_OLD = /[0-9]{9}[x|X|v|V]$/; // Regular Expression 1
const NIC_REGEX_NEW = /[0-9]{12}$/; // Regular Expression 2
@Component({
selector: 'sample-form',
templateUrl: `sample.html`,
styleUrls: ['sample.css']
})
export class SampleComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
sampleFormControl = new FormControl('', [
Validators.pattern(NIC_REGEX_OLD)
]);
}
this is the HTML content for the above field
<div class="sample">
<md-form-field>
<input mdInput required [formControl]="sampleFormControl" maxlength="12">
<md-error *ngIf="sampleFormControl.hasError('pattern')">
Please enter the valid sample input
</md-error>
</md-form-field>
</div>
for a single regular expression(single pattern) this is working fine, but since I need to validate two patterns I tried following approaches in typescript file
Approach 1:
sampleFormControl = new FormControl('', [
Validators.pattern(NIC_REGEX_OLD || NIC_REGEX_NEW)
]);
Approach 2:
sampleFormControl = new FormControl('', [
Validators.pattern(NIC_REGEX_OLD),
Validators.pattern(NIC_REGEX_NEW)
]);
But none of above working properly, is it possible to validate multiple patterns using md-error ? please comment
What you were trying was combination of pattern(AND
condition) should satisfy together then only the field will be valid. But actually you need either of RegEx
to be satisfied, so that's why consider creating a custom validator
which would manually testing both the RegEx with OR
operator.
Code
function validateInput(c: FormControl) {
let NIC_REGEX_OLD = /[0-9]{9}[x|X|v|V]$/; // Regular Expression 1
let NIC_REGEX_NEW = /[0-9]{12}$/; // Regular Expression 2
return (NIC_REGEX_OLD.test(c.value) || NIC_REGEX_NEW.test(c.value)) ? null : {
validateInput: {
valid: false
}
};
}
//Usage
sampleFormControl = new FormControl('', [
validateInput
]);
See Also Custom Validators in Angular
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