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

``Error Message: TypeORM - could not establish database connection

I encountered an issue while running my project built with Typescript, Typeorm, and Express. The error message received when running the dev script was: connectionNotFoundError: Connection "default" was not found The content of my ormconfig.json ...

Fade In Effect in Angular 2 Using SwitchCase

Hi everyone, I'm facing an issue with making my switch cases fade in after one is called. Here's what I have so far. When the correct switch case is entered in the input field, I want the current one to fade out and the new one to fade in. How ...

Ways to customize the OverridableComponent interface within Material-UI

Is there a way to effectively use the Container component with styled-components incorporating ContainerProps, while still being able to pass the component prop that belongs to the OverridableComponent interface? Currently, I am encountering an error when ...

Combining Data in Angular and Firestore: Exploring the Power of Observables

I am attempting to retrieve a profile document using valueChanges and combine it with session data. However, when I utilize forEach, the observable returned is null (I'm still new to both technologies). The following code successfully re ...

The componentWillReceiveProps method is not triggered when a property is removed from an object prop

Just starting out with React, so I could really use some assistance from the community! I am working with a prop called 'sampleProp' which is defined as follows: sampleProp = {key:0, value:[]} When I click a button, I am trying to remo ...

Having trouble resolving npm install -g @angular/cli due to issue with checking the installable status of [email protected] module

When attempting to install @angular/cli using the npm command in the command prompt, I encountered an issue with resolveWithNewModule. It seems to be stuck at checking installable status.[email protected] ...

What is the best way to manage error handling in various locations within an Angular stream?

Currently, I am working on ensuring that errors are handled properly in a stream where the id of a group is retrieved first and then used to obtain profile information. I want to easily identify whether the error is occurring during the retrieval of the g ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

How to extract key-value pairs from an object in a TypeScript API request

I am trying to extract the data '"Cursed Body": "100.000%"' from this API response using TypeScript in order to display it on an HTML page. Can anyone help me figure out how to do this? API Response { "tier": &q ...

Solving issues with Angular4 Router changes

I'm attempting to chain the router resolver for my application. Below are my Router options: { path: '', component: AdminComponent, resolve: [ SessionResolve, LocaleResolve ] } The desired flow is to first call S ...

Error message "Angular build with --prod causes Uncaught TypeError: e is not a constructor when running ng serve"

I am encountering an issue while deploying my Angular application to production. The application functions correctly in development and had previously worked on production as well. To build the application, I am using: ng build --prod --base-href="/site/ ...

What is the most effective way to retrieve data from a URL and process it using reactjs?

Looking to consume JSON data from a URL, here is an example of the JSON structure: { "results": [ ... ], "info": { ... } } I aim to display the fetched data as a component property. What is the most efficient way to achie ...

Having trouble modifying the fields in the formArray

Working with reactive forms, I have a UI feature that displays radioButton options which, when selected, reveals details about the chosen value within the form. Once a button is selected, the form fetches data from the backend. The structure of my form is ...

The element of type 'any[]' cannot be assigned to type '[id: string]'

My goal is to develop a versatile API structure, where the properties are functions that return Promises. export type API = { [key: string]: <Params extends any[], Response>(...params: Params) => Promise<Response>, } export interface User ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...

Accessing files from various directories within my project

I'm working on a project with 2 sources and I need to import a file from MyProject into nest-project-payment. Can you please guide me on how to do this? Here is the current file structure of my project: https://i.stack.imgur.com/KGKnp.png I attempt ...

Ngrx/effects will be triggered once all actions have been completed

I've implemented an effect that performs actions by iterating through an array: @Effect() changeId$ = this.actions$.pipe( ofType(ActionTypes.ChangeId), withLatestFrom(this.store.select(fromReducers.getAliasesNames)), switchMap(([action, aliases ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...

Error encountered while utilizing the Extract function to refine a union

I am currently working on refining the return type of my EthereumViewModel.getCoinWithBalance method by utilizing the Extract utility type to extract a portion of my FlatAssetWithBalance union based on the generic type C defined in EthereumViewModel (which ...

Translate from one category to a different one

I often encounter a common issue - how can I efficiently convert one type to another? For instance, extending an object received from the server with UI-specific properties. interface RawData { id: number someOtherData: string } interface ViewData ex ...