Display an error message whenever the mouse leaves the input field

Can someone please help me with how to display an error message in Angular4 when the input field is required and the mouse leaves the input? I want the error to show only when the mouse leaves the input, not while I am typing within the input field.

Here is my code:

<input type="email" class="form-control" name="email" placeholder="Enter email" [(ngModel)]="data.email" #dataemail="ngModel" required minlength="12" pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" >
<div *ngIf="dataemail.errors?.pattern" class="alert alert-danger">Email is invalid</div>

The error message currently displays in div.class="alert alert-danger" as soon as text is typed into the email input field. How can I make it so that the error message shows only when the mouse leaves the input field?

Answer №1

To activate the validation upon blur, make sure to specify the updateOn option as 'blur'. This will ensure that the validation is triggered only when the user moves out of the input field.

<input 
  [(ngModel)]="data.email"
  [ngModelOptions]="{ updateOn: 'blur' }" <!-- include this -->
  type="email" 
  class="form-control"
  name="email" 
  placeholder="Enter email"
  #dataemail="ngModel" 
  required 
  minlength="12"
  pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$">
</div>
<div *ngIf="dataemail.errors?.pattern" class="alert alert-danger">
  The email provided is invalid
</div>

Experience live demo here

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

A step-by-step guide on how to access the version number in an Angular (v4+) application from the package

Currently, I am attempting to retrieve the version number of my Angular application from package.json where it is stored. Most resources recommend using require to load the JSON file like so: var pckg = require('../../package.json'); console.log ...

Unable to activate the date range picker

I am having trouble with integrating the daterange picker on my webpage. I can't seem to get it to work properly. Can anyone help me figure out what I might be doing wrong or if there's something missing? CSHTML: <div class="has-feedback" &g ...

What could be causing this test to fail when testing my API endpoint?

Why am I encountering this error? Uncaught exception: Error: listen EADDRINUSE: address already in use :::3000 import supertest from "supertest" import axios from "axios" import app from ".." const request = supertest(app ...

The main server is not yielding any results from the MongoDB query

I attempted to utilize promises in order to retrieve all the items from my mongoDB database. Here is the code I used: exports.findAll = function(){ return new Promise(function(resolve, reject){ Collection.find({}, function(err, res){ if(err ...

Comparing strings with if-else statement

I am having trouble comparing strings in this array. For some reason, the strings are never equal. var person = ["Sam", "John", "Mary", "Liz"]; var searchedName = prompt("Enter name"); var resultMessage = ""; for (index in person) { var currentName = ...

Is it possible to include if else logic code within a catch statement?

There's a nagging feeling within me that having logic code within a catch statement is not the right approach. For example, my catch block currently looks like this: try{ // do some stuff that throws some unexpected errors } ...

Contrasting deleting a node_module folder with running npm uninstall to remove a specific package

Do manual deletion of a package directly from the node_modules folder and running npm uninstall really make any difference, considering that npm just deletes the package anyway? ...

Angular.js encountered an error at line 13550: [ng:areq] The argument 'popCntrl' is expected to be a function, but it was undefined

I have been diving into learning AngularJS on my own recently, and I've been attempting to create a basic popup feature. However, I keep encountering the error mentioned in the title. While searching for solutions, I haven't found any examples th ...

Having trouble retrieving a JSON result from a method located in a different namespace

In my project, I have organized my code into separate .js files and namespaces for json requests and actual logic. Despite this organization, I am facing issues with retrieving the result back in my logic layer. var jsonResult = Blah.Data.LoadAggregates( ...

Module augmentations do not allow for exports or export assignments

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'; declare module 'kvl' { export = kvl; } declare const kvl: { ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void; ...

Multer throws error when trying to upload files as an array instead of individually, displaying an 'Unexpected File Error'

Multer is a key module utilized in conjunction with node js and express for file uploads. On the angular side, I am utilizing the ng-file upload module. When sending multiple files individually, everything works smoothly without any errors. However, when ...

After running a yarn build on a TypeScript project using a .projenrc.js file, make sure to include any packaged or additional text files in the lib folder, rather

After utilizing projen to create my typescript project, I followed these steps: mkdir my-project, git init, and npx projen new typescript. Additionally, I created two files - sample.txt and sample.js, along with the default file index.ts within the folder ...

extracting the key name from a JSON object using JavaScript

Consider the following JSON object: { "A" : {"A1": "1" } } I am wondering how to retrieve the value of the key A1 from this JSON object. This way, I can assign it to a variable in JavaScript such as: var index = "A1"; ...

Sending output from javascript back to html

<head> function displayProductName(name) { } </head> <body> <img src="...images/car.jpg" onclick="displayProductName('car')"> </body> How can I modify this javascript function to display the value received from t ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

When configuring the Redux logger, the type 'Middleware<{}, any, Dispatch<UnknownAction>>' is not compatible with type 'Middleware<{}, any, Dispatch<AnyAction>>'

In my React project, I have defined the redux logger with the package version "redux-logger": "^3.0.6" in the file store.ts as shown below: import { configureStore } from '@reduxjs/toolkit'; import rootReducer from '@/re ...

Prisma and Next.js: Changes to content require re-deployment for updates to take effect

Just recently, I launched a new website on Vercel. My web application is being built with Prisma and Next.js. However, I'm currently facing an issue where the content doesn't update in real-time unless I manually re-deploy the application. Here&a ...

Tips for closing a notification popup from the NzNotificationService

I'm currently utilizing NG-ZORRO Notification Here is my Angular code snippet: this.notif = this.notification.create( 'success', 'Notification', 'test message' ); I haven't been able to locate any API meth ...

Comparing object variables within Javascript's HTMLCollection

let var1, var2; // Obtaining elements from the HTMLCollection var1 = document.forms[0]; var2 = document.forms.item(0); alert(var1 === var2); // Output: "true" var1 = document.forms["myForm"]; var2 = document.forms.namedItem("myForm"); alert(var1 === v ...

Trouble with transmitting props to function

The child component is not receiving the props as expected. When printed, it displays an empty object. The problem seems to be in the News.js file specifically related to passing props to the child component from App.js. All functions are operational excep ...