Guide to implementing personalized validation for an angular component

In my Angular component, I am looking to implement a custom input validator. However, I am facing an issue while trying to access the ngModelController in the $onInit function. It seems that the form is not populated at this stage. Strangely, in the sendEmail() function, I have no problem accessing the input model controller. How can I successfully access the ngModelController and add a custom validator to it?

This is the code snippet for emailInput.js:

(function(angular) {
  'use strict';

  function EmailInputController($log) {
    var ctrl = this;

    ctrl.$onInit = function() {
      // The line below shows that ctrl.myForm.myEmailInput is not populated 
      //$log.debug("Email view value is: "+(ctrl.myForm.myEmailInput.$viewValue));
    };

    ctrl.sendEmail = function() {
      $log.debug("EmailInputController.sendEmail");
      $log.debug("Email view value is: " + (ctrl.myForm.myEmailInput.$viewValue));
    };

  }

  angular.module('emailInputApp').component('emailInput', {
    templateUrl: 'emailInput.html',
    controller: EmailInputController,
  });
})(window.angular);

This is the code snippet for emailInput.html:

<form name="$ctrl.myForm">
  <label>Email:</label>
  <input name="myEmailInput" type="email" ng-model="$ctrl.email" required maxlength="15">
  <button type="button" ng-click="$ctrl.sendEmail()">Send Email</button>
  <p>Your Email address is {{$ctrl.email}}</p>
  <div ng-messages="$ctrl.myForm.myEmailInput.$error" role="alert">
    <div ng-message="required">Please enter an email address.</div>
    <div ng-message="email">This field must be a valid email address.</div>
    <div ng-message="maxlength">This field can be at most 15 characters long.</div>
  </div>
  <code>
    {{$ctrl.myForm.myEmailInput | json}}
  </code>
</form>

Answer №1

http://example.com/codeSnippet123

One helpful tip is to add a watcher and then remove it when it is no longer needed.

var stopWatching = $scope.$watch('$ctrl.myForm', function () {
        $log.debug("Checking value of email input: " + (ctrl.myForm.myEmailInput.$modelValue));

        stopWatching();
      });

Answer №2

app.directive('checkValidityEmail', function() {
  var EMAIL_PATTERN = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;

  return {
    require: 'ngModel',
    restrict: '',
    link: function(scope, element, attributes, control) {
      // only apply the validator if ngModel is present and Angular has added the email validator
      if (control && control.$validators.email) {

        // this will overwrite the default Angular email validator
        control.$validators.email = function(value) {
          return control.$isEmpty(value) || EMAIL_PATTERN.test(value);
        };
      }
    }
  };
});

Add the following to your HTML:

<input type='email' validate-email name='email' id='email' ng-model='email' required>

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

How can I interpret a string with a specific format using JavaScript?

Input String: var json_data = "{0:'apple', 1:'bannana', 2:'guava'}"; Desired Output after parsing with JavaScript: var json_data = { columns: [{0:'apple'}, {1:'bannana'} ,{2:'guava'}] ...

Changing from system mode to dark mode or light mode

Within my Next.js web application, I am implementing MUI to facilitate the transition between system, light, and dark modes. Persistence between sessions is achieved by storing the selected theme in local storage. The user has the option to change the them ...

What is the proper way to handle postMessage events from a Streamlit iframe within a Next.js app?

I'm currently in the process of integrating a Streamlit app into a Next.js application by embedding the Streamlit within an iframe. My main goal is to send data from the Streamlit app to the Next.js parent using window.postMessage, specifically focusi ...

Cleaning out input fields in React applications

When I click on the <button type="submit" className="btn btn-primary">Create</button>, a card with hero is generated. Then, using .then(() => clearFields()), I am able to clear the input fields so that clicking the Create ...

The process of eliminating line breaks in javascript is not functioning as expected

I've been searching all over the place, experimenting with different methods, but I just can't seem to fix this issue.. var save_field = res[0]; var save_value = res[1]; save_value = save_value.replace(/\n/gm, '<br />'); con ...

Minimizing Jitter in HTML5 and JavaScript Applications

I am currently working on developing a metronome as a hobby using JavaScript/HTML5 with the intention of turning it into a FirefoxOS app. One issue I've encountered is Jitter, which is unacceptable for Metronomes. As JavaScript is single-threaded and ...

Enhance the list visualization in Next.js by efficiently transferring data from child components

In my Next.js Page component, I have a setup similar to the following: export default function Index({ containers }) { const [containerListState, setContainerListState] = useState(containers); const updateContainerList = (container) => { contai ...

Execute function after AngularJS returns data

My dilemma revolves around calling a callback function while struggling to retrieve the necessary data due to an error in my method. Here is what I have attempted: //function with callback filterList: function(type, cb) { if (type == 'all') { ...

Creating a variable in Node.js to serve as the name of a nested element within an object

Check out the object I have: obj = { "FirstName": "Fawad", "LastName": "Surosh", "Education": {"University": "ABC", "Year": "2012"} } Take a look at my node.js script: var nodeName = 'Education.Year'; obj.nodeName; // ...

How can I extract data from an XML file and include it in a JSON file using GulpJS?

Being relatively inexperienced with Gulp/Node programming, I am facing some difficulties while trying to accomplish a simple task :) Within my XML file, there exists a node like the following: <widget version="1.1"></widget> My goal is to ext ...

Experiencing issues with the redirect button on the navigation bar of my website

Video: https://youtu.be/aOtayR8LOuc It is essential that when I click a button on my navigation bar, it will navigate to the correct page. However, since the same nav bar is present on each page, it sometimes tries to redirect to the current page multiple ...

Guide on transforming the popup hover state into the active state in vue.js through a click event

My code currently includes a popup menu that shows up when I hover over the icon. However, I need to adjust it so that the popup changes its state from hover to active. Intended behavior: When I click the icon, the popup should appear and then disappear w ...

Error: The JavaScript SRC cheat is malfunctioning

Having an issue with the code below. The 'dummy1' and 'dummy2' variables are not loading their content as expected on the page. Any suggestions? <html> <head> <title>JavaScript On-line Test</title> <script LA ...

In my Next.js project, I am looking for a way to make a modal continue to stay

I am looking to implement a feature where the modal remains visible even after a website refresh. Currently, when a user logs out, the page refreshes and the modal displaying "sign-out successful" disappears. My goal is to have the modal reappear after t ...

How is UI Router Extras causing unexpected errors in my unit tests?

QUESTION: - I am facing failures in my tests after installing ui-router-extras. How can I resolve this issue? - Is there a way to use ui-router-extras without causing test failures? If you want to quickly install this, use yeoman along with angular-full ...

Issue with Bootstrap side navbar not collapsing when clicked on a link

Currently, I'm working on creating a website for a friend. While I used to have some experience with coding in the past, it has been a while and I am a bit rusty. This time around, I decided to use bootstrap for the project. However, I'm struggli ...

Guide on transforming 3D obj files into particles using three.js

I've been experimenting with particles in three.js, but I've encountered an issue when trying to convert an obj file (3D model) into particles. Here are the code snippets I've been working with, but so far all my attempts have failed. Does ...

My HTML file is not able to load my Javascript file

I'm currently working on integrating a JavaScript code for a show more and show less feature on my page. The goal is to limit the description so that it shows only a certain number of characters, with an option to expand or collapse the text. However, ...

Dynamic way to update the focus color of a select menu based on the model value in AngularJS

I am looking to customize the focus color of a select menu based on a model value. For example, when I choose "Product Manager", the background color changes to blue upon focusing. However, I want to alter this background color dynamically depending on th ...

What is the most efficient way to organize JSON data in a tree structure using JavaScript?

I have a JSON data structure that I need to transform into a different format. The original JSON format: values = an array containing objects that need to be filtered by action === 'commented' comment = an object with the comment, n Tasks, and ...