Displaying an error message prior to submitting the form in an AngularJS form validation process

I have implemented form validation using angularjs, but I am encountering an issue where the error message is displayed upon page load instead of after an actual error. I have set up a validation summary using a directive. Can you please advise me on how to resolve this?

Below is my code:

<label>UserName</label>
<input type="text" class="form-control" name="UserName" ng-model="userVM.UserName" required ng-minlength="8" ng-maxlength="20" />
<div validation-message ng-show="customerForm.UserName.$error.required" class="error">
    Username is required
</div>

The directive is defined as follows:

NusPayApp.directive("validationSummary", function () {
    return {
        restrict: "A",
        require: "^form",

        template: "<div class='alert alert-warning'><a class='close' ng-click='toggleValidationSummary()'>×</a><h4 class='alert-heading'>Warning!</h4><li ng-repeat='(expression,message) in validationMessages'>{{message}}</li></ul></div>",
        link: function (scope, element, attributes, controller) {

            scope.validationMessages = {};

            // Watches for changes in the expression and message
            controller.watchValidation = function (expression, message) {

                scope.$watch(function () { return scope.$eval(expression); }, function (isVisible) {
                    var containsMessage = scope.validationMessages.hasOwnProperty(expression);

                    if (!containsMessage && isVisible) {
                        scope.validationMessages[expression] = message;
                    }

                    if (containsMessage && !isVisible) {
                        delete scope.validationMessages[expression];
                    }
                });
            };
        }
    };
});

Please provide suggestions on ensuring that the error messages are shown only after the form is submitted.

Answer №1

To determine if a form has been submitted, you can add a new variable to the scope.

$scope.isFormSubmit = false

If there are errors in the form, update this flag to true.

if($scope.form.$valid)
{
      //Submit the form
      $scope.isFormSubmit = false
}
else
{
     $scope.isFormSubmit = true
}

Make sure to modify your HTML code accordingly:

<div validation-message ng-show="customerForm.UserName.$error.required && isFormSubmit" class="error">
 Username is required
</div>

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

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

What is the method employed by the script to ascertain the value of n within the function(n)?

I've recently started learning about jQuery. I came across a program online that uses a function where the value of n starts from 0 and goes up to the total number of elements. In the example below, there is only one img element and jQuery targets thi ...

There appears to be a problem with the angular URL as it is

During a recent project, I encountered an issue with the URL functioning differently after some changes. Originally, when working locally, the URL worked fine by going to localhost:9000/ However, now the URL becomes http://localhost:9000/#/ After ...

Do AJAX requests make Cross-site scripting attacks more significant?

Currently, I am in the process of developing a React application that utilizes a PHP (Codeigniter) backend. Despite Codeigniter not handling this issue automatically, I have taken it upon myself to delve into the matter. While I comprehend the importance ...

Personal Information Management

After making a request for stormpath user custom data, I used the following code: res.render('home', { title: 'home', user: req.user.customData, }); Instead of receiving a JSON object of custom data as expected, a URL ('') ...

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

Javascript malfunctions upon refreshing the div

After updating data with an ajax function and refreshing the div, I encountered an issue where the jQuery elements inside the div break. How can this be resolved? function getURLParameter(name) { return decodeURIComponent((new RegExp('[?|&]&apo ...

Why is the imported package not being recognized in the namespace declaration of my Node.js TypeScript file?

Currently, I am utilizing the WebStorm IDE developed by JetBrains to modify a TypeScript file within a Node.js v8.6.0 project. The JavaScript version set for this project is JSX Harmony. In the beginning of the TypeScript source file, there is an import st ...

Manage the border around the image by incorporating a timer countdown - starting from a complete circle, transitioning to a partial arc, and finally disappearing completely

My expertise lies in html, css, and angularjs for front-end development. I have an image that is initially surrounded by a thick border forming a full circle. As a countdown of one minute begins, I want the border to gradually disappear as time progresses. ...

I was working with node.js when I encountered the following issue: 'server' is declared but its value is never read.ts(6133) from the line "var server = app.listen(3000, listening);"

While working on the 8.6 lesson in the api2 folder, I encountered an error/bug. Upon inspection of my server.js file, I identified and rectified the issue. However, when I revisited the api1 folder for the 8.5 lesson, everything was functioning correctly a ...

What is the best way to showcase the outcomes of a map function in JSX?

I'm currently learning react and working on implementing the searchMap function (to display movie title/poster) with the TMDB API. While I am able to successfully log the necessary information to the console, I am encountering issues such as undefined ...

Understanding Node.js document object

Hey, I'm currently trying to execute a JavaScript function on the server side using node.js, but I've encountered an issue. The function relies on accessing hidden values within the returned HTML using the document DOM, however, the document obje ...

The app is having trouble loading in Node because it is unable to recognize jQuery

I am currently using Node to debug a JavaScript file that includes some JQuery. However, when I load the files, the $ sign is not recognized. I have installed JQuery locally using the command npm install jquery -save-dev. The result of "npm jquery -versio ...

Creating an object efficiently by defining a pattern

As a newcomer to Typescript (and Javascript), I've been experimenting with classes. My goal is to create an object that can be filled with similar entries while maintaining type safety in a concise manner. Here is the code snippet I came up with: le ...

The navigation controller, responsible for updating navbar values, is only executed once

My goal is to construct a simple Angular application and familiarize myself with the basics. To start, I'm utilizing Yeoman's angular-generator for scaffolding. This generator comes with a predetermined .config featuring $routeProvider, which I ...

Discovering the window.scrollTop, ScrollY, or any other distance value while utilizing CSS scroll snap can be achieved by following these

I am currently utilizing css scroll snap for smooth scrolling through sections that are 100vh in height. The functionality of the scroll snap is quite impressive. However, I need to find a way to determine the exact distance the user has scrolled down the ...

Jquery plugin experiencing a malfunction

I am encountering an issue with my custom plugin as I am relatively new to this. My goal is to modify the properties of div elements on a webpage. Here is the JavaScript code I am using: (function($) { $.fn.changeDiv = function( options ) { var sett ...

What is the best way to adjust the vertical margin in a vis.js timeline?

The vis.js timeline sets a margin of 5px in each row using inline styles that are controlled programmatically by the library. The height, top position, and transform of each item within the row are specified by the library as well. Attempting to manually ...

Using React for form validation

I'm facing a challenge while trying to develop a user registration form, especially when it comes to displaying form validation errors. Issues: 1) The input fails to post (via axios) to the database upon submission for inputs without errors. 2) The e ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...