Enable the acceptance of various validator patterns within Angular Material 2

I'm using md-error in angular material to validate user inputs from the client side.

Currently, I am trying to validate an input field that accepts two types of patterns:

  1. Pattern 1: Accept the first 9 characters as numbers followed by the 10th character being either x, X, v, or V

  2. Pattern 2: Accept 12 characters as numbers only

In my TypeScript file, I have implemented this as follows:

samplefile.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';

const PATTERN_ONE = /[0-9]{9}[x|X|v|V]$/;
const PATTERN_TWO = /[0-9]{12}$/;

@Component({
    selector: 'sample-form',
    templateUrl: `sample.html`,
    styleUrls: ['sample.css']
})
export class SampleComponent implements OnInit {

    constructor() {
    }

    ngOnInit() {

    }       

    sampleFormControl = new FormControl('', [
        Validators.pattern(PATTERN_ONE)
    ]);    
}

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 a valid sample input
        </md-error>
    </md-form-field>
</div>

While validating a single pattern works fine, I encountered issues when attempting to validate two patterns simultaneously. I tried different approaches in TypeScript but none worked successfully. Is there a way to validate multiple patterns using md-error? Your insights are appreciated.

Answer №1

The attempt you made involved a combination of pattern (using the AND condition), where both conditions needed to be satisfied for the field to be considered valid. However, what you actually require is for either one of the regular expressions (RegEx) to be satisfied. Therefore, it is advisable to create a custom validator that will manually test both regular expressions using the OR operator.

Custom Validator 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
]);

For more information on custom validators in Angular, check out this article.

Answer №2

Combine your two regular expressions into one string using a |, then utilize a single

Validators.pattern ("your expression")
.

An example of this could be

Validators.pattern("/[0-9]{9}[x|X|v|V]$/|/[0-9]{12}$/")
. In this case, an "or" is used to separate the two regex patterns.

Answer №3

If you are working with Angular 7 or a newer version, try the following approach:

checkInputValidity(c: FormControl){ //Implementing Dual Pattern Check 
    let originalPattern = '^[A-Z]{2}[0-9]{2}[A-HJ-NP-Z]{1,2}[0-9]{4}$'; // First Regular Expression 
    let newPattern = '^[0-9]{2}BH[0-9]{4}[A-HJ-NP-Z]{1,2}$'; // Second Regular Expression
    return (c.value.match(originalPattern) || c.value.match(newPattern)? null :{invalidAddress : true}); }

//example of how to use it 
registrationNo: new FormControl('', [Validators.required, this.checkInputValidity])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Typescript error: The value "X" cannot be assigned to this type, as the properties of "Y" are not compatible

Disclaimer: I am relatively new to Angular2 and typescript, so please bear with me for any errors. The Challenge: My current task involves subtracting a start date/time from an end date/time, using the result in a formula for my calculation displayed as " ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...

Issue during Docker build: npm WARN EBADENGINE Detected unsupported engine version

Currently, I am constructing an image based on mcr.microsoft.com/devcontainers/python:0-3.11-bullseye. In my docker file, I have included the following commands towards the end: RUN apt-get update && apt-get install -y nodejs npm RUN npm install np ...

Updating documents within an array in MongoDB is a common task that can be easily accomplished

Trying to modify a specific property within my MongoDB document. This is how the document is structured: "_id" : ObjectId("57e2645e11c979157400046e"), "id" : 1651570992420, "creator" : "nameHere ...

Launch a TypeScript Node.js server on Heroku deployment platform

I'm having trouble deploying a Node.js server built with TypeScript on Heroku. Despite following various tutorials and searching through Stack Overflow for solutions, I can't seem to make it work. Here is the code I have in my tsconfig.json and p ...

Running a website on a virtual server

I am working on a webpage that presents results from an angular application, and I want to host it on a web server located on my virtual machine. This will allow my team members to easily access the page daily. However, I am unsure of how to proceed with ...

What could be causing the resolve method to not send any data back to the controller?

While following a tutorial on YouTube, I encountered an issue with incorporating the resolve method getposts into the contactController. Despite my efforts, no value is being returned. I've spent hours searching for answers on Stack Overflow to no av ...

Obtain the date format of the current locale script in use

When I need to i18n my application, I dynamically import the locale script: $scope.setCountry = function(countryKey) { // Importing Angular locale dynamically based on country select var imported = document.createElement('script' ...

Please proceed by submitting all radio buttons that have been checked

Seeking assistance with creating a quiz application using the MEAN stack. Once all questions are attempted, there will be a submit button for checking all selected radio buttons - option 1 corresponds to 1, option 2 to 2, and so on. The current structure o ...

Tips for effectively validating with ParsleyJS remote validator?

I've been trying to solve a problem for hours now, but I can't seem to figure out how to retrieve a value in php and pass it back to js. Here is the input field in question: <input type="text" class="form-control input-lg" name="nr_ref" id=" ...

Having trouble with localstorage.setitem function in Angular?

Check out the function below. I can see an object in the console.log using res: login2(){ console.log(this.user_form_value); console.log(this.password_form_value); this._loginService.login(this.user_form_value, this.password_form_value).subscr ...

Is it possible to blend HTML and Jade routes in a single project?

I am interested in setting up an application where I can incorporate a mix of both HTML and Jade. While I don't have anything against Jade, I prefer working with HTML for building applications involving Angular and Node APIs. As I am currently learnin ...

Trigger AngularJS functionality upon the completion of loading a Partial routed by Express

I'm fairly new to AngularJS and recently ran into an issue that's been keeping me up at night... Our application is built on node.js and express, with all partial routing handled by Express. The problem I'm facing is this: Whenever I load ...

Error: Can't compile - Accordion controller is necessary

Encountered the following error in the console while using angular-bootstrap ui. My setup includes angular 1.2.6, bootstrap 3.0, and angular-bootstrap 0.10.0. Error: [$compile:ctreq] Controller 'accordion', required by directive 'accordionG ...

Trouble with updating scope values in the view within IONIC 1 and AngularJS

I recently implemented a feature to save the two most recent login details. The functionality works correctly, but I'm facing an issue where my view only updates upon refresh even though the scope values are being updated. I've tried using $scop ...

Tips for choosing a visible element in Protractor while using AngularJS

I am working on a Single Page Application that contains multiple divs with the same class. My goal is to have protractor identify the visible div and then click on it. However, I keep encountering the error Failed: element not visible, which leads me to be ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...

Error in Fullcalendar Angular/Node.JS http request: Circular structure detected during JSON conversion (at Object.stringify)

Encountering a "TypeError: Converting circular structure to JSON at Object.stringify (native)" error while attempting to update by http call on fullcalendar drop event. Below is the client side code snippet: drop: function() { $scope.schedule. ...

What causes the 'then' method of my angular service to return a resolved promise instead of the expected value?

I am perplexed as to why the "result" in this code snippet is a resolved promise instead of the actual value: searchService.getLink(vm.queryObject).then(function (result) { console.log(result); }); The implementation for the getLink() function is pro ...

Integrate a fully developed ReactJS 16.x application seamlessly into an existing AngularJS 1.x framework

On a current project I'm working on, there's a unique challenge where I need to incorporate a compiled ReactJS app into an existing AngularJS project, with the Chrome/Firefox browser serving as the end-user interface. This setup isn't ideal, ...