Setting validation in Angular for either of two fields to validate in reactive form approach

I'm currently working on setting up user form validation, where the user must input either their mobile number or email address.

Below is the HTML code for adding a guest reaction form:

<form class="new_guest" id="new_guest" [formGroup]="addGuestForm" (ngSubmit)="onSubmit()">
            <div class="form-group">
                <input placeholder="Enter guest name" class="add-guests form-control ui-autocomplete-input" type="text" formControlName="name"
                    id="guest_name" autocomplete="off">
            </div>
            <div class="form-group">
                <input placeholder="Enter guest email" class="add-guests form-control ui-autocomplete-input" type="text" formControlName="email"
                    id="guest_email" autocomplete="off">
            </div>
            <div class="form-group">
                <input placeholder="Mobile Number, If any" class="add-guests form-control ui-autocomplete-input" type="text" formControlName="mobile"
                    id="guest_mobile" autocomplete="off">
            </div>
            <input type="submit" class="btn btn-default btn-block" id="add_guest" value="ADD GUEST" [disabled]="!addGuestForm.valid">
        </form

This is how the structure of AddGuest init looks like:

this.addGuestForm = new FormGroup({
  'name': new FormControl(null, Validators.required),
  'email': new FormControl(null, Validators.email),
  'mobile': new FormControl(null)
})

If you have any suggestions or solutions, please feel free to share. Thank you!

Answer №1

To create a custom form with validation in Angular, you can utilize the form builder and define specific criteria for validation. Here's an example:

this.customForm = this.formBuilder.group({
'name': new FormControl(null, Validators.required),
  'email': '',
  'phone': ''
}, {
      validator: (formControl) => {
        var emailCtrl = formControl.controls.email;
        var phoneCtrl = formControl.controls.phone;

        if (emailCtrl != undefined && phoneCtrl != undefined)
             if (!(emailCtrl.value.length || phoneCtrl.value.length ))
                    return {invalid: true};
}
});

Additionally, you can incorporate regex pattern matching for the email field by defining a variable called regexPattern for the email pattern check. Use the following line in the custom validator if condition:

regexPattern.test(emailCtrl.value)

Answer №2

Dealing with a similar issue led me to create a custom validator:

export function requiredControlValidator(...controls: AbstractControl[]): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
        for (const aControl of controls) {
            if (!Validators.required(aControl)) {
                return null;
            }
        }
        return { requiredControl: true };
    };
}

You can integrate it like this:

this.form.setValidators([
  requiredControlValidator(
      this.form.get('firstName'),
      this.form.get('lastName'),
  )
]);

If needed, you may consider adjusting the requiredControlValidator function to take input parameters as controlNames: string[] instead of AbstractControl[].

For a demonstration, refer to this example.

Answer №3

Modifying the response provided by @pogiaron to include setting the error key that is returned.

function checkForOneRequired(errorType: string, ...controlItems: AbstractControl[]) {
    return (control: AbstractControl): ValidationErrors | null => {
        for (const item of controlItems) {
            if (!Validators.required(item)) {
                return null;
            }
        }
        return { [errorType]: true };
     };
}

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

Access specific properties of an object in TypeScript using dot notation with the

Can we use dot notation to extract nested object elements in TypeScript? interface Test { customer: { email: string; name: { firstName: string; }; }; }; type PickedTest = ExtractNested<Test, "customer.name.firstName"> ...

JavaScript Date() function misinterpreting Unix timestamp

When creating the date using a timestamp retrieved from Firebase, I use the following code: let da = new Date(item.date.day); I have double-checked that item.date.day is indeed a timestamp and the correct one at that. However, regardless of the actual t ...

The variable 'VAR_PLURAL' is not defined within this type

While working with angular 8.x i18n, I encountered a peculiar error message that seems to be quite unique (as most i18n errors tend to be; referring to you, https://github.com/angular/angular-cli/issues/7555#issuecomment-394228634). The error message read ...

Angular service is able to return an Observable after using the .then method

I am currently facing an issue with retrieving the authentication status in a service method. Everything seems to be working fine except for the return statement. I am struggling with the usage of .then inside .map and I am unable to figure out how to retu ...

Having trouble with Angular routing when attempting to directly access a specific URL path?

Seeking help with my routing setup in Angular. Using v12 of Angular. Encountering a 404 Not Found error when trying to access the direct URL for "register" at somesite.com/register. Uncertain if this is a server or Angular issue. Here is my router module ...

Confirm that the input value consists of x numeric characters

Looking to validate an input field that must contain a minimum of x amount of numeric characters. For example, let's say I require the input value to have at least 5 numeric characters: 12345 - valid AB12345 - valid 123456 - valid AB312312 - valid a ...

The implementation of TypeScript 3.5 resulted in a malfunction where the imported namespace was unable to locate the Enum during runtime

I recently upgraded an older Angular.js application from Typescript 2.7 to 3.5 and successfully compiled it using tsc.exe. During application runtime, I encountered an error message in certain parts of the code: TypeError: Cannot read property 'Enu ...

Mastering the Use of Interfaces in Ionic/Angular

My journey into angular/ionic app development is just beginning. I came across the following piece of advice recently Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. Curre ...

ngx-datatables in Angular is experiencing issues with its filtering options

Having trouble implementing a filter option in ngx-datatables for all columns. I've written the code but it's not functioning correctly. Can anyone help me identify where I went wrong and find solutions? app.component.html: <label> Nam ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

Printing HTML in Angular 8

I am encountering an issue with my simple angular 8 application. When I try to print an HTML part in my angular component, it works fine in the development build. However, when I deploy the application in the production build, the print document opens and ...

What could be causing the Intellisense errors in Visual Studio 2015 that say "Cannot find module 'angular2/core'"?

Currently, I am utilizing Visual Studio 2015 Update 1 in conjunction with TypeScript 1.8.5. Within my ASP.NET MVC 4.6 Web Application, Angular2 is being used. The TypeScript compile options have been configured with the following settings: <PropertyG ...

Ineffectiveness of ngFor in displaying content within a component in Ionic 5

Feeling a bit overwhelmed here, I've successfully created a new component and it's working perfectly. Now I want to use this component on two different pages. To make things easier, I decided to create a component module (/components/all-compone ...

Creating an Escape key press event in plain Typescript without using JQuery

Is there a way to trigger an Escape button press event in Angular unit tests? const event = document.createEvent('UIEvent'); event.initUIEvent('keydown', true, true, window, 0); (<any>event).keyCode = 27; (<any ...

The withLatestFrom operator in RxJS is not functioning as anticipated

I have a user input observable called userInput$ that emits data streams every N seconds while the user is typing into an input field. I want to take the latest input and pass it as a parameter to the function service.search(x), which will then return anot ...

What is the method for importing styles in Next.js without including the file extension?

I've got a project set up with Next.js, TypeScript, and SCSS. In every app/*/page.tsx or components/*/page.tsx, there's a line importing the stylesheet like import style from "styles/*/index.module.scss". I find these lines to be too lo ...

Ways to transfer arguments from a subclass component to its superclass

Currently in the process of upgrading from Angular 7 to Angular 12. I have multiple components that inherit from a shared base class, where constructor arguments are passed in. Main Component export abstract class PageBase implements OnDestroy{ const ...

Issue encountered: The function this.http.post in Ionic 3 is not recognized as a valid function

As someone who is new to Ionic 3 & Angular 4, I am currently working on creating a login page that sends email and password data to an API. However, I keep encountering the error message "this.http.post is not a function". Despite my efforts to find a solu ...

Ways to add parameters to each external URL using Angular

Seeking thoughts on implementing a feature in Angular to append a parameter to all external URLs or URLs from a specific domain. Let's take as an example. If I were using jQuery, I could achieve this on document ready by doing something like: $(‘ ...

A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implemen ...