Show validation messages using ng-messages depending on various conditions

Implementing angular ng-messages for validation message display

Check out this code snippet:

<ul ng-messages="formToValidate.fieldToValidate.$error" ng-messages-multiple>
    <li ng-message="pattern">Invalid pattern</li>
    <li ng-message="minlength, maxlength">Input should be 7 to 100 characters long</li>
    <li ng-message="!pattern && !minlength && !maxlength && onlyAfterAllOtherPassedValidation">
        Displayed when all previous validations pass and onlyAfterAllPassedValidation fails
    </li>
</ul>

I'm seeking a way to show the last validation message only if all other checks have passed but "onlyAfterAllPassedValidation" fails. I am unsure how to pass a complex condition to ng-message. Any tips or alternative solutions are appreciated as long as ng-messages can still be used.

Answer №1

To apply the ng-if directive to the container of the message, you can follow this example:

<li ng-if="!formToValidate.fieldToValidate.$error.required && !formToValidate.fieldToValidate.$error.minLength && !formToValidate.fieldToValidate.$error.maxLength" ng-message="onlyAfterAllOtherPassedValidation">
    This specific validation message will only appear if all other validations have been successful and fails on onlyAfterAllOtherPassedValidation
</li>

Answer №2

It's true that the solution suggested by JonMac1374 works. However, it's always better to find a permanent fix for this issue. I recommend checking out the use-form-error directive. It can help you create your own validation checks.

You can see a live example on jsfiddle.

<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" name="password" minlength="2" pattern="^\d*$" required use-form-error="onlyAfterAllOtherPassedValidation" use-error-expression="!ExampleForm.password.$error.required && !ExampleForm.password.$error.minlength && !ExampleForm.password.$error.pattern"
  />
  <pre>{{ExampleForm.password.$error|json}}</pre>
  <div ng-messages="ExampleForm.password.$error" ng-messages-multiple="true" class="errors">
    <div ng-message="required">
      Your required input is incorrect
    </div>
    <div ng-message="pattern">
      Your input doesn't match the required pattern
    </div>
    <div ng-message="minlength">
      Your input is too short
    </div>
    <div ng-message="onlyAfterAllOtherPassedValidation">
      Your validation failed after all other conditions passed
    </div>
  </div>
</form>

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

Solving Mixed Content Issues in JavaScript

I'm attempting to retrieve information from OMDB API, but I'm encountering an issue with mixed content images. OMDB pulls its data from IMDB, which does not allow the use of https images. Therefore, all image sources must be prefixed with http. ...

Uncovering the secrets: accessing hidden folder files in react-native-fs

I am encountering a problem when trying to access files from a hidden folder /WhatsApp/Media/.Statuses in react-native-fs. Despite granting the READ_EXTERNAL_STORAGE permission on Android, I only receive an empty array when attempting to access it using th ...

"Dynamic" visual in a Vue.js development scheme

Utilizing Vue.js for the development of a hybrid mobile application has been my current focus, with the Quasar framework serving as a key component. Recently, I incorporated an image into the application using the <img /> tag and utilized the followi ...

Guide on incorporating Vue components: implementing component 2 within the template of component 1

I'm a Vue beginner and struggling with how to use one component within the template of another or how to combine them in HTML. I've tried looking through the documentation and Stack Overflow but can't seem to figure it out. Currently, I am ...

Unusual activity observed in HTML5 contenteditable functionality

Within a list item, I have a span element. <ul> <li>text part 1 <span class="note">this is a note</span> text part 2 </li> <li>text part 3</li> </ul> When you double click on th ...

Is a Singleton really necessary for my situation?

I am currently developing a Firefox extension that requires keeping multiple windows synchronized with the same information. The toolbar in each window queries a remote server periodically, but since Firefox windows are isolated environments with their own ...

Unable to send data using GET method after implementing passportjs integration

In the route.js file, I have implemented the following REST method: app.get('/api/todos', isAuthenticated, function(req, res) { DB.TodoTable.find() .exec(function(err, todos) { res.json(todos, function(err){ if (err) ...

Struggling to iterate through the response.data as intended

Assume that the response.data I have is: { "data": { "person1": [ { "name": .... "age": xx } ], "person2": [ { ...

Should we opt for Controlled components or Uncontrolled components when it comes to working with HTML forms in React

I am currently faced with a decision on where the best location is for housing my Form State. The React documentation states: Identify every component that renders something based on that state.  Find a common owner component (a single component above ...

A JavaScript syntax problem arises when attempting to fetch data (an object) from a Laravel controller

Encountering a JavaScript syntax error in my .blade.php file when trying to access $data->modal This is my controller function: public function buku_all($page, $modal) {$data = (object) [ 'sidebar' => "pelayanan", ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

Guide to changing an image on a canvas with KineticJS

I am currently working on developing a canvas that will display a hotel floor view. I have images stored in a database which I am drawing onto the canvas using x and y coordinates from the database as reference points. However, I want to add touch events t ...

What steps can be taken to resolve the dependency problem with npm installation?

Attempting to incorporate npm install react-material-ui-carousel --save into my react project has presented a challenge. Upon installation, I encountered a dependency tree issue. Even after deleting the lock and npm modules files, followed by running npm ...

Struggling to get a basic HTML form to function with JavaScript commands

In my form, there are two input fields and a button. Upon clicking the button, a JavaScript function is triggered which multiplies the values entered in the inputs. The result is then displayed in a <p> element and evaluated through an if else statem ...

Utilizing shared data properties in both JavaScript and SCSS within Vue

Vue.js 2 has caught my interest, especially with the single-file component structure: <template> <h1>Hello World</h1> </template> <script> export default { name: 'hello-world', }; </script> <style s ...

Strategies for Handling Logic in Event Listeners: Choosing Between Adding a Listener or Implementing a Conditional "Gatekeeper"

What is the most effective way to manage the activation of logic within event listeners? In my experience, I've discovered three methods for controlling the logic contained in event listeners. Utilizing a variable accessible by all connected sockets ...

Improving code structure for a unique date feature

I've successfully built a date component (see GIF below). The code is functioning as intended, but I feel it's a bit convoluted and may be difficult for others to grasp. Note: Please refer to the GIF below. Ignore the styling. This is how I&ap ...

Hold off on running the code until the image from the AJAX request is fully loaded and

Currently, I am facing a challenge with my code that aims to determine the width and height of a div only after it has been loaded with an image from an AJAX request. The dimensions of the div remain 0x0 until the image is successfully placed inside it, c ...

Tips for integrating Angular 2 with different websites and modules while utilizing PHP as the backend

I am looking to transition to using more industry-standard practices by starting my front-end development with Angular 2 instead of my custom JS MVC-framework. However, I am encountering some challenges while working with Angular and would like to address ...

New patch request received in Google Sheets, replacing the existing post request

I am transferring 12 cell values from a Google Sheet to a MongoDB database. The purpose behind this action is to merge the 12 cells, perform certain data transformations, and display the output on a frontend interface later on. Moreover, I'm faced wit ...