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

"Exploring the symbiotic relationship between Node.js and Express.js: an

I recently started learning Node.js and Express.js. I used the Express.js executable (express) to create an express application, which generated the following lines in app.js: ... var app = express(); http.createServer(app).listen(app.get('port' ...

Running tests to check for next(err) functionality using supertest and Express JS

When using Express in a route or middleware, you can halt the callback chain by calling next(err) with any object as err. This feature is well-documented and simple to understand. However, I encountered an issue when testing this behavior with SuperTest. ...

What are the steps for incorporating a YouTube playlist into a website?

I'm in the process of creating a website and I'd like to incorporate a YouTube video playlist that looks similar to this example - http://www.youtube.com/user/icicibank/home. I plan to use HTML5, JavaScript, and the YouTube API. Can you provide g ...

"XMLHttpRequest 206 Partial Content: Understanding the Importance of Partial

I need help with making a partial content request using an XMLHttpRequest object in JavaScript. Currently, I am trying to load a large binary file from the server and want to stream it similar to how HTML5 video is handled. While setting the Range header ...

Unable to pass props to component data using Vue framework

I'm facing an issue with passing props in my component to the same component's data object. For some reason, I'm only receiving null values. Does anyone have any suggestions on how I should approach this problem? It seems like my Vue compone ...

How to change numbers into words using AngularJS

Could someone assist me with converting numbers into words using AngularJS? For instance, if the amount I receive from a service is 9876, I would like it displayed as "Nine Thousand Eight Hundred and Seventy Six" in a table. Please provide guidance on how ...

A guide to displaying dropdown values above a modal

I have encountered an issue while using a dropdown inside a modal window. The problem is that not all the dropdown values are visible, as the overflow part gets hidden. I am looking for a solution to keep the dropdown value at the top and prevent it from b ...

Error: Trying to break down a non-iterable object is not valid

Currently working on an Ionic React app and encountering the following error: Error: TypeError - Invalid attempt to destructure non-iterable instance Once I run the program, the error occurs at this point: . Shown below is a snippet of my code: import ...

The content of a Puppeteer page mysteriously disappears when transferred to another function

My current project involves using Puppeteer for web scraping on my website. I encountered a strange issue where the await page.content() works fine when I console log the content, but turns out to be null when passed as an argument to another JavaScript ...

angularJS transformRequest for a specified API call

Looking for a way to pass multipart/formdata through a $resource in Angular so I can post an image. I discovered a helpful solution on this Stack Overflow thread. However, the solution applies to all requests within my modules, and I only want it to apply ...

AngularJS redirection through routing

My requirement is to display a list of items with edit and delete links. When the user clicks on edit, an edit form should appear with textboxes and a save button. After the user edits the data and clicks on save, the data should be saved and the listing p ...

What is the best way to convert a 2D PHP array into a JavaScript array?

I have encountered a problem with a PHP array setup as follows: $output = array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3)); When I encoded the array to JSON, I received this output: $output = {"1":[1,1,1,1],"2":[2,2,2,2],"3":[3,3,3,3]} My goal is to ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

Error: The property 'scrollIntoView' cannot be read because it is null

class MessageApp extends Component { constructor(props) { super(props) this.state = { text: "", messages: [] } } componentDidMount() { const config = { apiKey: "<api-key>", authDomain: "<projec ...

Is there a way to programmatically fetch files from a MySql / Node.js server?

I've been working on my CRUD app and I'm currently focusing on downloading files from a MySql Nodejs server. Here are the steps I have accomplished so far: I created a function in userContoller.js to query the MySql database for the id=179 (just ...

Material-UI icons refusing to show up on the display

I've been working on creating a sidebar component and importing various icons to enhance the UI, but for some reason they are not displaying on the screen. I even tried other suggested solutions without success. <SidebarOption Icon = {InsertComment ...

Supporting traditional IE document compatibility within an iFrame

Currently, I am facing an issue with my web application which is being used in an iframe by a web portal (SAP enterprise portal). The portal is responding with the header x-ua-compatible IE=EmulateIE7, causing complications for my AngularJS-based applicati ...

Utilizing JavaScript to Retrieve Selected Parameter in SSRS Report

Currently, I am incorporating an SSRS report into my website using Iframe. I aim to share a link to the specific filtered report, which is why I require knowledge of the report's parameters. My query pertains to how I can identify these parameters (e ...

Parsing JavaScript JSON using PHP's json_decode method is a powerful feature

In my current scenario, I am encountering situations where I extract a JSON string from an HTML page and pass it to the `json_decode` function. Sometimes it succeeds, but other times `json_decode` returns null. How can I enhance my solution to ensure that ...

What is the method for determining the new point coordinates and direction vector after a rotation of degrees in three.js?

How can I determine the coordinates of point A to H after rotating a certain number of degrees and aligning them with direction vector (-42, 51, 11) using three.js? Thank you in advance for your help and please forgive any mistakes in my English. Best reg ...