Concealing errors during field updates in Angular form validation

Currently, my form consists of just one field with a few validation rules:

<form name="my_form" novalidate ng-controller="FormController">
            <label>Your Name:</label>
            <input type="text"
                   name="name"
                   placeholder="Your Name"
                   ng-model="form.name"
                   ng-minlength="3"
                   ng-maxlength="20"
                   unique
                   required />
            <button ng-click="submitForm()">Submit</button>
            <div class="error"
                   ng-show="my_form.isSubmitted"
                   ng-messages="my_form.name.$error">
                <div ng-messages-include="errors.html"></div>
            </div>
        </form>
        

The field undergoes validation for:

  • Minimum length
  • Maximum length
  • Required input
  • Uniqueness (custom validation rule)

I utilize ng-messages to exhibit error messages close to the input field. Here's my errors.html template:

<div ng-message="required">This field is required.</div>
        <div ng-message="minlength">This field is too short.</div>
        <div ng-message="maxlength">This field is too long.</div>
        <div ng-message="unique">The value of this field must be unique.</div>
        

Validation only commences post the 'Submit' button click (submitForm() function triggers my_form.isSubmitted flag and releases my error div).

Below is my JavaScript code:

var app = angular.module('formValidation', ['ngMessages']);

        app.controller('FormController', function($scope) {
          $scope.submitForm = function() {
            $scope.my_form.isSubmitted = true;
          };
        });

        app.directive('unique', function() {
          return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, ele, attrs, ctrl) {
              var names = ['Dmitry', 'Alexander', 'Elizabeth'];
              ctrl.$parsers.push(function(value) {
                if (names.indexOf(value) > -1) {
                  ctrl.$setValidity('unique', false);
                  return false;
                }
                ctrl.$setValidity('unique', true);
                return true;
              });
            }
          };
        );
        

While everything functions smoothly, I now aim to hide errors upon field modification after they've been displayed (until the submit button is pressed again).

One approach could be adding another condition to the ng-show directive of the error div to verify if the corresponding field is updated. If so, errors should stay hidden. For instance:

<div class="error"
               ng-show="!my_form.name.isUpdated && my_form.isSubmitted"
               ng-messages="my_form.name.$error">
            <div ng-messages-include="errors.html"></div>
        </div>
        

Thus, on button press, I can set the isUpdated flag of all form fields to false and update it to true on any input changes. However, this solution feels somewhat inelegant. I'm certain there exists a better method to achieve this behavior. Any suggestions?

Answer №1

Below is my current implementation, although it may not be optimal:

<input type="text"
           name="name"
           placeholder="Your Name"
           ng-model="form.name"
           ng-minlength="3"
           ng-maxlength="20"
           unique
           updatable
           required />
    <button ng-click="submitForm()">Submit</button>
    <div class="error"
           ng-show="!my_form.name.isDirty && my_form.isSubmitted"
           ng-messages="my_form.name.$error">
        <div ng-messages-include="errors.html"></div>
    </div>

I recently included a new directive called updatable for my input field and adjusted the condition to display the error message as follows:

ng-show="!my_form.name.isDirty && my_form.isSubmitted"

The custom directive looks like this:

app.directive('updatable', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, ele, attrs, ctrl) {
      ele.bind('input', function() {
        scope.$apply(function() {
          ctrl.isDirty = true;
        });
      );
    }
  };
});

Additionally, I made a minor modification to the submitForm function to reset the isDirty flag of my field(s) to false upon submission:

$scope.submitForm = function() {
    $scope.my_form.isSubmitted = true;
    $scope.my_form.name.isDirty = false;
};

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 you confirm the mobile type, please? Using JavaScript to display a div only once based on the mobile type

Is there a correct way to determine the type of mobile device I'm using? Are there alternative methods to check for the mobile type? Take a look at my approach in the code below. How can I test this using a tool? Does anyone have insights on checki ...

Strange outcome received from THREE.JS - Vector3.project function

Currently I am working on a project in THREE.JS and I am encountering an issue with projecting a Vector3. When attempting to project the Vector3 (0,0,0), which should ideally appear at the center of my camera screen, I receive NaN as the result. Surprising ...

Dial the Google App Scripts hotline

After successfully testing the query string in the browser for my published app script, I attempted to send an XMLHttpRequest to the script. However, upon doing so, I encountered the following error message: XMLHttpRequest cannot load https://script.goo ...

Executing a JavaScript function within a Vue component script

I'm working on a simple component file for submitting a form, along with a JavaScript function to handle an action: <template> <div> <div class="modal-header"> <button type="button" class="close" data-dismi ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

Addressing the delay of "Rasterize Paint" on mobile devices while implementing css3 opacity transitions

I'm currently working on a project that involves users navigating back and forth between modals. To achieve this, I decided to use CSS transitions to change the opacity from 0 to 1. However, I've encountered some issues with slow transitions. So ...

The Angular build is unsuccessful due to the presence of components from a separate Angular project

Whenever I execute ng build project1 --prod, the build fails and displays this error message: ERROR in : Cannot determine the module for class MyComponent in .../project2/app/my.component.ts! Add MyComponent to the NgModule to fix it.. Although the sol ...

What is the best way to execute two asynchronous calls sequentially in JavaScript?

When using a common generic function for AJAX calls, the initial request retrieves all data from the server and maintains it within local scope. However, subsequent requests are still hitting the server, even when the data is already available locally. Thi ...

Jquery attribute not functioning correctly when setting the 'required' property for checkboxes

One of the challenges I am facing is trying to toggle a text box on a checkbox's click event. While I have achieved success in this aspect, my issue lies in changing the checkbox's required attribute as well. Below is the code that successfully ...

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...

Modify the Calendly widget CSS with a media query to adapt it to different screen sizes

Hey there, I'm new to CSS and I'm struggling with getting rid of the vertical scroll bar that shows up on mobile for a calendly widget. Here's the embed code for the widget: <div class="calendly-inline-widget" data-url="https://cale ...

What methods can I use to prevent unauthorized access to my JavaScript files?

By using Minify, I am able to minify and cache all of my script requests. I want to restrict access for users to only the minified versions of JavaScript files. My Minify setup can be found at www.example.com/min, while my scripts are located at www.examp ...

What are the best ways to enhance performance for ajax requests using Jquery?

Currently, I am in the process of developing a mobile application that utilizes jquery mobile, jquery, and a PHP backend. My issue arises when dealing with certain pages as there are numerous ajax requests being sent and received simultaneously, resulting ...

Uniting the graphical user interface with the server side operations

Greetings fellow developers! I am diving headfirst into the world of Stack Overflow and coding, so please bear with me as I navigate this new territory. Currently, I have crafted a sleek front end for a web application using a trifecta of HTML, CSS, and J ...

Creating a dynamic number of datasets in Chart JSWith Chart JS

After extensive searching, I thought I was on the verge of finding a solution several times, but unfortunately, no luck! I am aware that a similar question was posted yesterday: React Chartjs, how to handle a dynamic number of datasets, but it remains una ...

What occurs to the bound event once the DOM element disappears?

What happens if I attach an event handler to a DOM element and then remove the DOM element? Do I need to unbind the event handlers? <div id="el1"> <span id="c">Click Me!</span> </div> <span id="note">Note...</span> ...

Obtaining a result from a Promise in AngularJS

Here is a snippet of an Angular JS Service that I have: 'use strict'; app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) { var out = ...

Creating a Sudoku game board using underscore templates

Currently, I am in the process of constructing a Sudoku board using underscores templating. However, I have hit a roadblock when it comes to tackling the mathematical aspects necessary for deriving the table structure. My approach involves utilizing a 1d ...

JavaScript maintain a variable that holds onto nodes even after they have been removed

Recently, I encountered a seemingly simple issue with JavaScript that has me stumped. In my code, I have a variable that stores nodes with a specific class. My goal is to remove these nodes from the DOM while still retaining them in the variable. However, ...

Implement a mandatory parameter in the URL route using ui-router

My Angular routing configuration using ui-router is quite simple: $stateProvider .state("master", { abstract: true, url: "/{tenantName}" }) .state("master.home", { url: "", }) .state("master.login ...