What could be causing the unexpected behavior in my NgMessages form validation?

I have developed a code that incorporates Angular JS form validation methods.

There are two separate forms within the codebase, The initial form utilizes basic form validation

while the second form employs ng-messages,

However, an issue has arisen where the second form is not functioning properly compared to the first one.

The first form consists of 3 text fields,

with the last field set as required.

Upon loading the page and attempting to submit the form without filling it out, an error message appears next to each respective field.

If the text field is not empty but requires number validation, inputting text will trigger only the number validation error message.

Unfortunately, I am facing challenges in replicating this same validation behavior in my second form using ng-Messages.

The code snippet is displayed below,

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <title>Validator Examples</title>
    <script type="text/javascript" src="/home/rahul/Installers/jquery-3.0.0.js"></script>   
    <script type="text/javascript" src="/home/rahul/Installers/angular.js"></script>
    <script type="text/javascript" src="/home/rahul/Installers/Bootstrapv3.0.2/js/bootstrap.js"></script>

    <link rel="stylesheet" href="/home/rahul/Installers/Bootstrapv3.0.2/css/bootstrap.css">
    <link rel="stylesheet" href="/home/rahul/Installers/Bootstrapv3.0.2/css/bootstrap-theme.css">


    <script type="text/javascript">
        angular.module("myApp",[]);
        angular.module("myApp").controller("myCtrl",myCtrl);
        function myCtrl(){
            var vm = this;
            vm.formOne = {}
            vm.formOne.name = "";
            vm.formOne.address = "";                
            vm.formOne.age = 0;

            vm.formTwo = {}
            vm.formTwo.name = "";
            vm.formTwo.address = "";                
            vm.formTwo.age = 0;
        }
    </script>
    <style type="text/css">
        .form-error{
            color : red;
        }
    </style>
</head>
<body ng-controller="myCtrl as vm">
    <div class="container">
        <div class="page-header">
            <h3>Validator Examples</h3>
        </div>
        <div class="row">
            <div class="col-md-4 col-md-offset-2">
                <div class="page-header">
                    <h5><b>ngForm Validator Examples</b></h5>
                </div>
                <form name="formOne" novalidate>
                    <div class="form-group">
                        <input type="text" class="form-control" name="name1" placeholder="Name" required ng-model="vm.formOne.name"
                         minlength="5" maxlength="10" />
                        <div ng-show="formOne.$submitted || formOne.name1.$touched">
                            <div ng-show="formOne.name1.$error.required" class="form-error">Name can't be empty</div>
                            <div ng-show="formOne.name1.$error.minlength" class="form-error">Name can't be less than 5</div>
                            <div ng-show="formOne.name1.$error.maxlength" class="form-error">Name can't be more than 10</div>
                        </div>  
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" name="address1" placeholder="Address" ng-model="vm.formOne.address"
                         required />
                        <div ng-show="formOne.$submitted || formOne.address1.$touched">
                            <div ng-show="formOne.address1.$error.required" class="form-error">Address can't be empty</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <input type="number" class="form-control" name="age1" placeholder="Age" ng-model="vm.formOne.age"
                         required number/>
                        <div ng-show="formOne.$submitted || formOne.age1.$touched">
                            <div ng-show="formOne.age1.$error.required" class="form-error">Age can't be empty</div>
                            <div ng-show="formOne.age1.$error.number" class="form-error">Age should be numeric</div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div><!-- row -->
        <div class="row">
            <div class="col-md-4 col-md-offset-2">
                <div class="page-header">
                    <h5><b>ngForm ngMessages Validator Examples</b></h5>
                </div>
                <form name="formTwo" novalidate>
                    <div class="form-group">
                        <input type="text" class="form-control" name="name1" placeholder="Name"
                        ng-model="vm.formTwo.name" required ng-minlength="5" ng-maxlength="10" />
                        <div ng-messages="formTwo.name1.$error" 
                        ng-show="formTwo.$submitted || formTwo.name1.$touched" class="form-error" role="alert">
                            <div ng-message="required">Name can't be empty</div>
                            <div ng-message="minlength">Name can't be less than 5</div>
                            <div ng-message="maxlength">Name can't be more than 10</div>                
                        </div>  
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" name="address1" placeholder="Address" ng-model="vm.formTwo.address"
                         required  />
                        <div ng-messages="formTwo.address1.$error"
                         ng-show="formTwo.$submitted || formTwo.address1.$touched" class="form-error">
                            <div ng-message="required">Name can't be empty</div>                                
                        </div>
                    </div>
                    <div class="form-group">
                        <input type="number" class="form-control" name="age1" placeholder="Age" ng-model="vm.formTwo.age"
                         required number />
                        <div ng-messages="formTwo.age1.$error" ng-show="formTwo.$submitted || formTwo.age1.$touched"
                          class="form-error">
                            <div ng-message="required">Age can't be empty</div>
                            <div ng-message="number">Age should be numeric</div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                </form>
            </div>
        </div><!-- row -->
    </div>
</body>     

To provide a comparison:

In the first form, the validation for the initial file appears as:

<form name="formOne" novalidate>
                    <div class="form-group">
                        <input type="text" class="form-control" name="name1" placeholder="Name" required ng-model="vm.formOne.name"
                         minlength="5" maxlength="10" />
                        <div ng-show="formOne.$submitted || formOne.name1.$touched">
                            <div ng-show="formOne.name1.$error.required" class="form-error">Name can't be empty</div>
                            <div ng-show="formOne.name1.$error.minlength" class="form-error">Name can't be less than 5</div>
                            <div ng-show="formOne.name1.$error.maxlength" class="form-error">Name can't be more than 10</div>
                        </div>  
                    </div>

Contrastingly, the validation setup in the second form exists as follows:

<form name="formTwo" novalidate>
                    <div class="form-group">
                        <input type="text" class="form-control" name="name1" placeholder="Name"
                        ng-model="vm.formTwo.name" required ng-minlength="5" ng-maxlength="10" />
                        <div ng-messages="formTwo.name1.$error" 
                        ng-show="formTwo.$submitted || formTwo.name1.$touched" class="form-error" role="alert">
                            <div ng-message="required">Name can't be empty</div>
                            <div ng-message="minlength">Name can't be less than 5</div>
                            <div ng-message="maxlength">Name can't be more than 10</div>                
                        </div>  

While only the invalid messages are displayed for the first form,

All the error messages are visible in the corresponding field within the second form.

You can access the functional code implementation at the following link:

FormValidation

Please feel free to point out any potential mistakes or areas of improvement. Thank you!

Answer №1

  • Ensure that you have included the angular-message.js file in your <script>

  • Next, inject ngMessages into the module as shown below

angular.module('myApp', ['ngMessages']);

  • Assign a controller alias using form="vm.formTwo" and use ng-messages="vm.formTwo....

Check out this live demo

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

What is the best way to transfer information from a service to my controller?

Currently, I am experimenting with the Ionic framework and learning AngularJS simultaneously. I have been working on implementing $q and asynchronous calls but facing some challenges. My goal is to parse a JSON file using GetJsonSpecials, pass it to GetDat ...

The integration of Raphaeljs library with SmartPhones opens up a world of

I recently incorporated the incredible JavaScript library, RaphaelJS, into my website to create maps, animations, and interactive features. Interestingly, I have observed that the scripts utilizing this library function seamlessly on iPhones but encounter ...

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

Exploring Amcharts using detailed JSON data

[{"SUM_PTS":{"datatype":"INTEGER","length":"8","value":"29903727","obfuscated":"false"},"SUM_TOTAL":{"datatype":"INTEGER","length":"10","value":"1644704985","obfuscated":"false"},"MID":{"datatype":"ALPHANUMERIC","length":"27","value":"Vendor 1","obfuscated ...

Testing the ui-router with an incorrect route for unit testing

After finding a helpful post on Stack Overflow about adding unit tests for ui-router, I decided to implement the following test: describe 'State: myApp', -> # Loading the module of the filter beforeEach module 'myApp' $rootS ...

Using jquery to dynamically change audio source on click

Is there a way to dynamically change the audio src using jquery? <audio id="audio" controls="" > <source src="" type="audio/mpeg" /> </audio> <ul id="playlist"> <?php if($lists) { foreach ($lists as $list) { ?> ...

I am in search of a method to rephrase the content while minimizing redundancy

I am looking to improve the code for handling two different conditions in the UI. Can someone suggest a better way to rewrite it? <i *ngIf="measures.length > 0"> <ul *ngFor="let m of measures"> <io-data-selection-row [text] ...

Transfer text from one form to a text field on a different website

I've created a form that allows users to input numbers in a field and then directs the page to a specific URL. Here's the code snippet: <html> <head> <meta charset="utf-8"> <title>Tracking</title> </head& ...

Calling Array.prototype.slice results in an array with no elements

As a beginner in Javascript, I am looking to save JSON request data to a sub document in a MongoDB database. My current approach involves converting the JSON request into an array and then utilizing the $push method to pass the array to the sub document. H ...

Is the CSS Transition Solely Active for the Introductory Animation?

I'm currently looking to enhance the smoothness of div expansion and contraction on hover using CSS transitions. However, I have noticed that the Transition property only seems to affect the entry animation (i.e., when the mouse hovers and the div exp ...

Missing ng-required fields not displaying the has-error validation in AngularJS forms

While editing any part of their address, the user should see a red invalid border around each field to indicate that the full form is required. However, for some reason I can't seem to get the 'Address' field to display this border. The set ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

What is the best way to create a function library that works seamlessly across all of my Vue.js components?

I am currently in the process of developing a financial application using Vue.js and Vuetify. As part of my project, I have created several component files such as Dashboard.vue Cashflow.vue NetWorth.vue stores.js <- Vue Vuex Throughout my development ...

AngularJS special filter is not retrieving any data

Having an issue with a new filter that is not receiving data: Here is my error log: Controller Code: angular.module('reklaApp') .controller('MainCtrl', function ($scope, $http, Reklas, Modal) { $scope.newRekla = {}; Reklas.getAll() ...

What is preventing me from displaying the results on the webpage?

Currently, I am utilizing Express alongside SQLite and SQLite3 modules. However, upon running the server, the data fails to display on the initial request. It is only after a page refresh that the data finally appears. I attempted a potential solution by ...

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 ...

Is there a missing X-AppEngine-Region in the headers of the AppEngine application?

I've been trying to access the Region and Country in my request, but it seems like the X-AppEngine-Region and X-AppEngine-Country headers are missing. Sometimes I see headers like alt-svc content-length content-type date etag server status via ...

Refreshing Javascript with AngularJS

I'm encountering an issue while starting my angular js application. On a html page, I have divs with icons and I want the background color to change on mouse over. This is working using jquery's $(document).ready(function(){ approach. The conten ...

Obtain the key's name from the select query

My task is to populate a select element from JSON data, but the challenge lies in the formatting of the JSON where the keys contain important information. I do not have control over how the data is structured. I am attempting to iterate through the JSON a ...

React and D3 Force Layout: uncharted territories for new links' positions

After carefully following the general update pattern for new React Props, I've noticed that D3 efficiently handles data calculation and rendering when receiving new props. This prevents React from having to render every tick. D3 functions seamlessly ...