Utilize multiple validators.patterns within a single value for enhanced data validation

I need to implement two different patterns for the formControlName='value' based on the type selected. If type is 'A', I want to use the valuePattern, and if type is 'B', I want to use the uname pattern.

This is my HTML code:

 <h1 mat-dialog-title>{{'DNS.Create entry' | translate }}</h1>
 <div mat-dialog-content fxLayout="row" fxLayoutAlign="center center">
<form name="createEntryForm" [formGroup]="createEntryForm" fxLayout="column" fxFlex="100">
    <mat-form-field>
        <mat-label>Type</mat-label>
        <mat-select placeholder="type" formControlName="type" [(ngModel)]="entrType">
            <mat-option  value="A">A</mat-option>
            <mat-option value="CNAME">CNAME</mat-option>
        </mat-select>
    </mat-form-field>
    <mat-form-field>
        <mat-label>Hostname</mat-label>
        <input matInput formControlName="hostname" [pattern]="unamePattern">
        <span matSuffix>.{{ domain.name }}</span>
        <mat-error *ngIf="hostname.errors?.pattern">{{'DNS.Hostname not valid' | translate }}</mat-error>
    </mat-form-field>
    <mat-form-field>
        <mat-label *ngIf="entrType == 'A'">{{'DNS.IP address' | translate }}</mat-label>
        <mat-label *ngIf="entrType == 'CNAME'">FQDN cible</mat-label>
        <input matInput formControlName="value">
        <mat-error *ngIf="value.errors?.pattern">
            {{'DNS.Value not valid' | translate }}
        </mat-error>
    </mat-form-field>
    <mat-form-field>
        <mat-label>TTL</mat-label>
        <mat-select placeholder="ttl" formControlName="ttl" [(ngModel)]="ttlType">
            <mat-option value="300">5 min</mat-option>
            <mat-option value="3600">{{'DNS.1 hour' | translate }}</mat-option>
            <mat-option value="86400">{{'DNS.1 day' | translate }}</mat-option>
        </mat-select>
    </mat-form-field>
</form>

{{'DNS.Cancel' | translate }} {{'DNS.Create' | translate }}

This is my TypeScript code:

 import { Component, Inject, ViewEncapsulation } from '@angular/core';
 import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
 import { Validators, FormBuilder, FormGroup } from '@angular/forms';
 import { Domain } from 'app/models/domain.model';


@Component({
selector: 'dnsaas-create-dialog',
templateUrl: 'dnsaas-create-dialog.component.html',
styleUrls: ['../dnsaas.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class CreateDialogComponent {
public entrType = 'A';
public ttlType = '86400';
unamePattern = "^[a-zA-Z0-9][a-zA-Z0-9\-\.]*[a-zA-Z0-9]$";
valuePattern = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";                                                                                            
 createEntryForm: FormGroup;
constructor(public createDialogRef: MatDialogRef<CreateDialogComponent>,
  @Inject(MAT_DIALOG_DATA) public domain: Domain,
   private _formBuilder: FormBuilder) { }

ngOnInit() {
  this.createEntryForm = this._formBuilder.group({
    domain_id: [this.domain.id],
    type: ['', [Validators.required]],
    hostname: ['', [Validators.required,    Validators.pattern(this.unamePattern)]],
  value: ['', [Validators.required, Validators.pattern(this.valuePattern)]],
  ttl: ['', [Validators.required]]
});
 }

onCancelClick(): void {
this.createDialogRef.close();
 }

get hostname() {
  return this.createEntryForm.get('hostname');
}

get value() {
  return this.createEntryForm.get('value');
}

}

I am looking to apply two different patterns in one value form field. How can I achieve this?

Answer №1

If you want to apply multiple validators to a single formControl, you can achieve this by using the compose method of the Validator class. For example:

hostname: ['', Validator.compose([Validators.required, Validators.pattern(this.userNamePattern)]),

Answer №2

To ensure custom validation, implementing a custom validator is necessary.

 createCustomValidator(c: FormControl) {
    if (c.dirty && c.value.name.test(this.pattern)) {
           // Implement your specific logic here utilizing the pattern to determine true/false
           return {
            validateConditionalPattern: {
                valid: false
            };
    } 
    return  null;
  }

This function can now be incorporated into other validators or used in conjunction with Validators.compose.

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

Is there a way to dynamically change the options in a dropdown menu using Angular?

I am facing an issue where the values in my dropdown list are changing to null when I click on the form. The add function is working correctly, but this update problem is bothering me. Can anyone provide assistance? Below is the snippet of my HTML code: ...

Consider pushing items onto an array only once when the condition is met, instead of adding to the array every

I have been tasked with importing Excel files containing customer orders into my web application. The process involves converting the data in the file into an object of arrays, where each array represents a row from the Excel sheet. Once the data is impor ...

I am experiencing difficulties with my Angular 8 NPM package as it is unable to locate its own

I am encountering an issue where my assets are successfully copied over to my scoped npm package, but they are not available after the application is served. Currently, the images in my application are searching for a path like this: https://localhost:420 ...

Avoiding Bootstrap loading in a Hyperledger Composer application

I am looking to eliminate the Bootstrap stylesheet from my Hyperledger Composer-compiled project. After compiling using yo hyperledger-composer and then running npm start, I noticed that when src/index.html is served at http://localhost:4200/, a Twitter B ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Unit Testing Angular: Mastering Unit Testing for the .map() Function

I am in need of testing a service method, but I am unsure about how to achieve complete coverage for the code that gets executed as a result of calling another injected service method. The Service Method to be tested: @Injectable() export class BomRevisi ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Browser with Node's https.Agent

In my npm package written in TypeScript, I utilize axios to make web requests. One of the endpoints requires certificate authentication, so I pass new https.Agent to axios to include the necessary certificates. Everything works perfectly when the module is ...

Utilize GroupBy and tally up items within an array using typescript

Here is a representation of my array, which is not a type of string but its own object called MyObject (similar to setter and getter objects in Java) ["Car","model","year","color","price"] ["Table" ...

"Unlocking Angular event intellisense in Visual Studio Code: A Step-by-Step Guide

Currently, I am enrolled in an Angular course on Udemy. The instructor prefers using VS Code as his code editor, and one interesting feature he showcased was when he tried to add events to a button element. As soon as he opened the parenthesis after the bu ...

pressing the button again will yield a new outcome

I am looking to disable a button (material ui) when it is clicked for the second time by setting disabled={true}. Unfortunately, I have not been able to find any examples related to this specific scenario on StackOverflow. <Button onClick={this.s ...

Gather the names of all properties from the filtered objects that meet specific criteria

Here is an example of an array: [ { "id": 82, "name": "fromcreate_date", "displayName": "From Create Date", "uiControl": "DATERANGE", }, { "id": 82, "name": "tocreate_date", "displayName": "To Create Date", "uiControl ...

Setting a condition for a function call when a checkbox is clicked

My table has columns labeled NoBill and Bill, with checkboxes as the values. Here is the default view of the table: https://i.stack.imgur.com/ZUvb2.png When the checkbox in the NoBill column is clicked, the total value (this.total) is calculated. The t ...

Is there a way to extract only the desired array object from a post API response using Angular's filtering mechanism?

I'm utilizing the getSearchBank() post API and receiving this particular response from it. This API provides me with a list of all banks stored in the database. (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {bankId: '616c07ca9d ...

Is it possible to apply two ngClass directives to a single div element in Angular 4?

When I click to start editing, a component is called for the editing process. In this component, I am unable to click on anything and the background turns black, which is okay. However, I would like for each ID that I select to edit to become active with a ...

Issues with Firebase Cloud Messaging functionality in Angular 10 when in production mode

Error: Issue: The default service worker registration has failed. ServiceWorker script at https://xxxxxx/firebase-messaging-sw.js for scope https://xxxxxxxx/firebase-cloud-messaging-push-scope encountered an error during installation. (messaging/failed-ser ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

The initial setting of [opened]="true" causes an issue with the Angular Material date range picker

Recently, we completed the upgrade of our app from Angular 14 to 15.2.9, which includes Angular Material. The migration process went smoothly, and now our app is compiling and running without any errors. However, we encountered an issue with the mat-date-r ...

Defining assertions with specified type criteria

Looking to do something special in TypeScript with a class called Foo. I want to create a static array named bar using const assertion, where the values are restricted to the keys of Foo. This array will serve as the type for the function func while also a ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...