The validation for the email field in Bootstrap, specifically in Angular 5, is not functioning properly for the "Email is Required

As a newcomer to Angular, I am seeking assistance with validation in my Angular 5 application. Specifically, I need to validate user emails and only allow navigation to a new component when a valid email is entered upon clicking a button.

While pattern validation works correctly, I am facing an issue where the "Email is required" message does not display when the email field is touched but left empty.

Additionally, I require the button to be clickable only after a valid email is inputted by the user.

<div class="col-12">
    <form>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="text" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" id="email" name="email" ngModel
                #emailref="ngModel">
            <div *ngIf="emailref.errors &&(emailref.touched || emailref.dirty)" class="alert alert-danger">
                <div [hidden]="!emailref.errors?.pattern">
                    Invalid pattern
                </div>
                <div [hidden]="!emailref.errors?.touched">
                    Invalid pattern
                </div>
            </div>

            <br>
            <button type="submit" routerLink="/createaccount" class="btn btn-primary">
                <i class="fas fa-user text-dark" style="font-size:20px"></i>
                Create An Account
            </button>
        </div>
    </form>
</div>

I would greatly appreciate any help in resolving these issues.

Answer №1

Here is the updated HTML Markup for you

<div class="col-12">
<form #myForm="ngForm">
    <div class="form-group">
        <label for="email">Email Address</label>
        <input type="text" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" id="email" name="email" ngModel
            #emailref="ngModel" required>
        <div *ngIf="emailref.errors &&(emailref.touched || emailref.dirty)" class="aler alert-danger">
            <div [hidden]="!emailref.errors?.pattern">
                Invalid email pattern
            </div>
            <div [hidden]="!emailref.errors?.emailref.touched">
                Email address is mandatory
            </div>
        </div>

        <br>
        <button type="submit" routerLink="/createaccount" class="btn btn-primary" [disabled]="myForm.invalid" >
            <i class="fas fa-user text-dark" style="font-size:20px"></i>
            Create An Account
        </button>
    </div>
</form>

Assign a reference variable 'myForm' to disable the button and Update the message in the second validation error

Answer №2

If you want to ensure data integrity, consider using ReactiveForms alongside the FormBuilder tool. This allows you to easily incorporate validators into your forms, such as:

this.form= this.fb.group({
  'email': new FormControl('', [ Validators.require Validators.email]
 });

To learn more about form validation and reactive forms, check out the official documentation links: Form Validation and Reactive forms

Answer №3

<div *ngIf="emailref.errors && (emailref.touched || emailref.dirty)" class="aler 
      alert-danger">
                <div *ngIf="!emailref.invalid?.pattern">
                    Incorrect pattern detected
                </div>
                <div *ngIf="(emailref.touched || emailRef.dirty)">
                    Please provide an email address
                </div>
</div>


    <br>
    <button type="submit" routerLink="/createaccount" class="btn btn-primary" [disabled]="emailref.invalid" >
        <i class="fas fa-user text-dark" style="font-size:20px"></i>
        Create A New Account
    </button>`

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 it possible to create an observable with RXJS that emits only when the number of items currently emitted by the source observables matches?

I am dealing with two observables, obs1 and obs2, that continuously emit items without completing. I anticipate that both of them will emit the same number of items over time, but I cannot predict which one will emit first. I am in need of an observable th ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

implementing dynamic visibility with ngIf directive in Angular

header.component.html <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a href="#" class="navbar-brand">Recipe Book</a> </div> <div class="collapse na ...

Angular website showing only app.component.html on the frontend

I'm currently working on developing the frontend for my API and I've encountered an issue while trying to create a new component. Despite my best efforts, including setting up an app-routing.module.ts file, my application only displays the conten ...

The module './login/servcioprueba1.service' is missing the exported member 'prueba'. Kindly add this member to resolve the issue

I am working on an Angular 8 project that involves a service file. To generate the service, I used the command: ng g s servicioprueba1 After generating the service, I imported it into my code as shown below. Included in Block 2 is the line where I impor ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

The push() method replaces the last item in an array with another item

Two objects are available: ej= { name="", code: "", namebusinessG:"", codebusinessG:"" }; group = { name:"", code:"" } Both of these objects will be stored in two arrays: groupList:any[]=[]; ejList:any[]=[]; The program flow s ...

Updating an array in a single line of code in Javascript can be achieved

Can the code below be optimized? const item: any; // New data const index: number = basketModel.data.coupons.findIndex( (x: any) => x.couponId === item.couponId ); if (index === -1) { // If new item, push it to array ...

The custom class-validator decorator in NestJS fails to retrieve the value from the parameter

In my Nestjs project, I have created a Custom ValidatorConstraint using class-validator. The purpose is to create my own decorator and apply it later on DTO classes for validations. Let's consider this route: foo/:client After a request is made, I w ...

Enhance the Error class in Typescript

I have been attempting to create a custom error using my "CustomError" class to be displayed in the console instead of the generic "Error", without any success: class CustomError extends Error { constructor(message: string) { super(`Lorem "${me ...

Is there a way to conceal an element within a component based on the current component being used with the router?

I have managed to hide an entire component, but I am unsure of how to show or hide specific elements within a component. export class AppComponent { headerFooterVisible: boolean; constructor(private router: Router) { router.events.subscribe(e =&g ...

Flying around in every essential element within a Vue template

Recently, I made the switch to Typescript for Vue and decided to enable the Volar extension. However, after doing so, I noticed that every HTML intrinsic element (such as section and img) is now being flagged as an error: JSX element implicitly has type &a ...

When I attempt to return an object from a function and pass the reference to a prop, TypeScript throws an error. However, the error does not occur if the object is directly placed in

Currently, I have the following code block: const getDataForChart = () => { const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; const test = { ...

Getting started with accessing an API using Angular 2

I am seeking a way to navigate outside of my Angular 2 application to mywebsite.com/api. This link should direct me to an API application hosted on the same server. Here is my current route configuration. export const routes: Routes = [ {path: '& ...

Mastering typing properties in React with TypeScript

Could someone please help me with this issue? I have created a basic react component. interface iRowData{ name: string } export default function ResultsSection(data: iRowData[]) { return <div>Results</div> } When I try to use it in ano ...

The issue of a malfunctioning react TypeScript map when used in conjunction with useContext

I am attempting to retrieve data from the TVMaze API using React, TypeScript, and useContext. Although I can display the data, the useContext does not update with the return value, so when I use the map function, nothing is displayed. Any advice on how to ...

Learn how to retrieve data outside of the .subscribe function in an Angular 2 polling service

// I'm facing an issue where I am unable to assign values from outside the subscribe function to any variable. In my current project, I am fetching JSON content using the http.post() method and storing it in a variable. However, I need to access this ...

Incorporate a typescript library into your Angular application

Recently, I added a text editor called Jodit to my angular application and faced some challenges in integrating it smoothly. The steps I followed were: npm install --save jodit Inserted "node_modules/jodit/build/jodit.min.js" in angular.json's bui ...

What is the best way to access the highest level form control within a validator function of a nested form group?

Is there a way to access the complete form within a validator function? I attempted using control.parent.parent, but it resulted in an error. private unitNumberValidator(hasMdu){ return (control: AbstractControl)=>{ let returnVal = null; //I need ...

Error: The variable _ is undefined when trying to use the .map() function on an array

While working on my project, I encountered a "ReferenceError: _ is not defined" when using the .map function in this code snippet: arr.map(async (elem) => { ... }); I couldn't find any explicit mention of "_" in my code. The error trace pointed me ...