Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allow to accept multiple validator patterns in angular material 2

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.

  1. Regular Expression 1 : Accept first 9 characters as numbers then 10th
    character as x or X or v or V

  2. 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

like image 708
Kelum Avatar asked Sep 07 '17 16:09

Kelum


1 Answers

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

like image 68
Pankaj Parkar Avatar answered Oct 14 '22 00:10

Pankaj Parkar