Displaying form errors in Ionic 3 when values do not match the specified regular expression

I have been working on creating validation forms using ionic/angular and I have successfully implemented checks for empty fields to notify the user that they need to be filled. However, I am now looking to also alert the user when their input does not match my specified validation pattern or regular expression. Additionally, I would appreciate some guidance on how to disable the submit button unless all validators are satisfied. Currently, I am only checking if each field has errors or has been touched.

Here is an example of my TypeScript file:

 // TypeScript code goes here
  

And here is a snippet from my HTML file:


// HTML code goes here

Answer №1

To see an example using a valid button, you can refer to the following code snippet:

    import { Component } from '@angular/core';
    import {Validators, FormBuilder, FormGroup } from '@angular/forms';

    @Component({
    template: `
    <form [formGroup]="todo" (ngSubmit)="logForm()">
      <ion-item>
        <ion-label>Todo</ion-label>
        <ion-input type="text" formControlName="title"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label>Description</ion-label>
        <ion-textarea formControlName="description"></ion-textarea>
      </ion-item>
      <button ion-button type="submit" [disabled]="!todo.valid">Submit</button>
    </form>
      `
    })

   export class FormsPage {
   private todo : FormGroup;

   constructor( private formBuilder: FormBuilder ) {
     this.todo = this.formBuilder.group({
       title: ['', Validators.required],
       description: [''],
     });
    }
    logForm(){
      console.log(this.todo.value)
     }
   }

Answer №2

Feel free to utilize the following code snippet:

    <ion-content>
  <form *ngIf="form" [formGroup]="form" (ngSubmit)="createItem()">
    <ion-list>
      <ion-item>
        <ion-label color="primary">{{ 'EMAIL_TITLE_INPUT' | translate }}</ion- 
          label>
        <ion-input type="email"  formControlName="email"></ion-input>
      </ion-item>
      <ion-item class="error-message" *ngIf="hasError('email', 'emailBadFormat')">
        <p text-wrap>Email is not valid</p>
      </ion-item>
      <ion-item>
        <ion-label color="primary">{{ 'PASSWORD_TITLE_INPUT' | translate }}</ion-label>
        <ion-input type="password"  formControlName="password"></ion-input>
      </ion-item>
      <ion-item class="error-message" *ngIf="hasError('password', 'passwordBadFormat')">
        <p text-wrap>Password must contain at least 1 uppercase Letter, 1 Number and must be between 4 and 12 characters long</p>
      </ion-item>
    </ion-list>
  </form>
</ion-content>

Include this in your TypeScript file :

import {InputValidators} from "./InputValidator";

constructor(formBuilder: FormBuilder) {

    this.form = formBuilder.group({
      email: ['', [Validators.required, InputValidators.emailValidate()]],
      password: ['', [Validators.required, InputValidators.passwordValidate()]],
      phone: ['']
    });
  }

hasError(field: string, error: string) {
    const ctrl = this.form.get(field);
    return ctrl.dirty && ctrl.hasError(error);
  }

Also, add the code below in InputValidator.ts:

import { AbstractControl} from "@angular/forms";

export class InputValidators {

  static passwordValidate() {
    return (control:AbstractControl): {[key:string] : boolean} => {
      if (!control.value || 0 === control.value.length) {
        return null;
      }

      if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,12}$/.test(control.value)){
        return null;
      }

      return {"passwordBadFormat": true};
    };
  }

  static emailValidate() {
    return (control:AbstractControl): {[key:string] : boolean} => {
      if (!control.value || 0 === control.value.length) {
        return null;
      }

      if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(control.value)){
        return null;
      }

      return {"emailBadFormat": 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

Can anyone suggest a more efficient method for validating checkbox selection in Angular?

I am working with an angular material stepper, where I need to validate user selections at each step before allowing them to proceed. The first step displays a list of 'deliveries' for the user to choose from, and I want to ensure that at least o ...

Is there a way to determine if a string within an array includes any special characters?

I am trying to determine if any string in an array contains special characters. I have experimented with various methods like RegExp, test, includes, and contains, but none of them give me the desired outcome. Instead, they all return false for every str ...

The versatile payment solutions offered by PayPal, including Adaptive Payments and Chained Payments, can be seamlessly

At this time, PayPal Adaptive Payments has been flagged as deprecated and there is no available frontend documentation. I have not been able to find a way to achieve this using the existing documentation. I am currently developing an Angular app that inte ...

Transforming a map into a plain object for TypeScript declaration

Here is a scenario: let cachedPromises: Map<string, Promise<any>> = new Map(); Can you provide the equivalent declaration for a plain object? Perhaps something along these lines: interface IMyMap { [key: string]: Promise<any> } let ...

One of the interfaces in use is malfunctioning, despite being identical to the other interface in TypeScript

I have been working on the IDocumentFilingDto.ts file. import { DocumentOrigin } from "./IDocumentFilingDto"; export interface IDocumentFilingDtoGen { UniqueId?: any; Title?: string; DocumentId?: string; Binder?: any; Communi ...

Is there a simple method to replace the base directive?

I am in search of an easy method to customize the behavior of default directives, like ngIf. By creating a child directive, I aim to enhance the existing functionality and then declare it as native. Note: I understand that altering standard functionality ...

Using TypeScript will result in errors when attempting to use the Promise object and the Awaited keyword

In this example, I am trying to ensure that the function foo does not accept a Promise as an argument, but any other type should be acceptable. export {} function foo<T>(arg: T extends Promise<unknown> ? never : T) { console.log(arg); } asy ...

Prevent external scrolling while Bootstrap modal is active

<div class="modal mt-5p" role="dialog" [ngStyle]="{'display':IONotes}"> <div class="modal-dialog modal-md mt-0px width-70p"> <div class="modal-content" style="height:500 ...

What is the process for adding my Ionic app to the share menu on an iPhone?

I'm working on an Ionic 3 app and I want it to be integrated into the iPhone share list just like shown in this example, https://i.sstatic.net/U2Lqr.png The Share option should appear when users access the gallery and then when they press the share b ...

Tips for verifying the Reactive formControl/formArray when submitting

In my scenario, I am working with a FormGroup titled Parent, which includes a FormArray as a control. This FormArray consists of another FormGroup referred to as the Child. Main Goal The main objective here is to perform validation on all controls of a sp ...

An error has occurred: Type 'x' is not compatible with type 'x' (during Vercel deployment)

I encountered an issue during Vercel deployment which displays the following error message: - Type error: Type ' ({ params }: DashboardPageProps) = Promise' is not compatible with type 'FC<.DashboardPageProps>' Type 'Promise ...

"Enabling browser.WaitForAngularEnabled(true) causes the browser to wait until the default jasmine time limit is

Currently, I am focused on Angular 4 test automation and utilizing the Protractor tool. Through various video tutorials, I have come to the conclusion that using WAIT functions for synchronization is unnecessary when working with Protractor. Whenever I inc ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

Issue encountered during execution of tests involving reactive forms

Having some issues with the code below and looking for a solution. The tests pass when mocking the form for ts tests, but encounter an error when mocking the same form for html: No value accessor for form control with name: 'Enable' If I remov ...

Angular2 - Issue with calling toPromise() method on this.http.get() function, as it is not recognized

I was following a tutorial on angular.io called Tour the Heroes, but instead of sticking to the tutorial I decided to make a real GET request for some JSON data. Here is a snippet of my code: private userUrl = 'https://jsonplaceholder.typicode.com ...

Empowering choices with Kendo for Angular

Back in the day when I used older versions of Kendo with Angular, I could easily configure my controls using a k-options attribute. <input kendo-date-picker k-options="monthPickerConfig"> Now that I'm using Kendo UI for Angular, I can't s ...

Issues with updating form inputs in Ionic 2's FormGroup item

Hey there, I'm just getting started with Angular 2 and I've been working on creating a basic form using FormBuilder and FormGroup. However, for some reason, the value I input into the username field in my view is not updating in my component. Whe ...

Using a package manager with Deno: Best practices and tips

I just learned about Deno, the alternative to NodeJS. I'm trying to figure out how to use yarn or npm with Deno, but I can't seem to find any instructions. Is there a way to use yarn or npm with Deno? ...

Setting up a winston logger in NestJS - A simple guide!

I am facing an issue with my nestjs app where I am trying to incorporate winston as a logger service. However, this implementation is causing my app to break and I am unsure how to resolve or revert this issue. I have attempted to uninstall the winston pa ...

The Typescript Compiler API Type Checker produces varying types from what is perceived by the Typescript Language support within the VS Code environment

Utilizing the Typescript Compiler API type checker, I am analyzing identifier nodes in a loaded file to determine their types within a program. To begin, I load the file and initialize the program and type checker like so: const program = ts.createProgram ...