Set all form fields to ng-touched programmatically when the form is submitted

HTML:

<div class="form-group" 
     ng-class="{ 'has-error' : form.firstName.$invalid && form.firstName.$touched }">
  <label for="firstName" 
         class="control-label">
         First Name
  </label>
  <input type="text" 
         name="firstName" 
         id="firstName" 
         ng-model="editableUser.firstName" 
         class="form-control" 
         required>
  <span class="help-block" 
        ng-show="form.firstName.$error.required && form.firstName.$touched">
        First Name is required
  </span>
</div>

<input type="submit" 
       ng-click="submit()" 
       value="Submit" 
       class="btn btn-default">

I want to apply the 'has-error' class to invalid fields when a user clicks submit.

This can be achieved by:

$scope.submit = function () {
  if ($scope.form.$invalid) {
    angular.forEach($scope.form.$invalid, function(field) {
      field.$setTouched();
    });
    alert("Form is invalid.");
  }
};

Initially, it was believed that $setTouched method does not exist in https://docs.angularjs.org/api/ng/type/form.FormController

UPDATE: It has been confirmed that $setTouched exists and is actually present in https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

Answer №1

if ($scope.form.$invalid) {
    angular.forEach($scope.form.$error, function (field) {
        angular.forEach(field, function(errorField){
            errorField.$setTouched();
        })
    });
    alert("Form is invalid.");
}

Plunker: Click here to view the Plunker code.

Answer №2

Check out the newest addition $submitted

<input type="text" 
     name="lastName" 
     id="lastName" 
     ng-model="editableUser.lastName" 
     class="form-control" 
     required>
   <span class="help-block" 
    ng-show="form.lastName.$error.required && (form.lastName.$touched || form.$submitted">
    Last Name is mandatory

Answer №3

Expanding on the solution provided by Alexey, you can enhance the FormController by creating a new method that accomplishes the same task. This eliminates the need to duplicate code from one submit function to another:

// customConfig.js
export default function customConfig($provide) {
    $provide.decorator('formDirective', $delegate => {
        const fn = $delegate[0].controller.prototype;
        if (!('$setTouched' in fn)) fn.$setTouched = function() {
            if (this.$invalid) {
                Object.values(this.$error).forEach(controls => {
                    controls.forEach(control => control.$setTouched());
                });
            }
        };
        return $delegate;
    });
}
// formController.js
$scope.submitForm = function () {
    if ($scope.form.$invalid) {
        $scope.form.$setTouched();
        alert("The form is invalid.");
    }
};

In situations where validation is necessary across platforms, such as dealing with iOS constraint issues, utilizing this type of validation ensures the ng-submit function only triggers on valid forms.

Answer №4

After trying various solutions, none of them were effective for me when it came to programmatically setting Touched to true.

For instance, even after running the code snippet

$scope.frmUser["U_Name"].$setTouched();
$scope.frmUser["U_Name"].$invalid
remained true.

I needed the submit button to be enabled only if $scope.frmUser.$invalid was false.

Ultimately, dynamically setting the scope variable for each field using JavaScript proved to be the successful approach.

Answer №5

If you prefer utilizing ES6 along with lodash functional programming

import forEach from 'lodash/fp/forEach'

    checkValidity()
    {
        forEach(forEach(field => field.$setTouched()))(this.form.$error)
    }

<form name="$ctrl.form">...</form>

Answer №6

None of the answers provided are suitable for the latest Angular v12 version. You can achieve the desired functionality with just a few lines of code:

submitForm() {
    this.form.markAllAsTouched();
}

Answer №7

No need to physically interact with the fields, opt for standard form validation instead; all you have to do is encompass your fields within a real form element and let angular handle the validation process for you. Check out this functional demo..

There's no necessity to validate against $touched or manipulate it (unless there's a specific reason prompting you to?) - just utilize the required attribute on input fields that are mandatory:

<input name="namefield" "text" ng-model="user.firstName" required/>

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

Converting HTML into an object using $compile

I am currently working on calling an HTML template and want to bind the data with Angular. I successfully retrieve the data to bind and the HTML, but when I try to compile it, it returns all the HTML binded as an object. How can I convert it back to plain ...

Angular 6 - Share content easily on mobile devices (IOS, Android)

After reviewing this example detailing the use of Angular 5 for copying to clipboard, I encountered issues when trying to run it on the iPhone 6s. Is there a more comprehensive solution available? ...

What is the main object used in a module in Node.js for global execution?

Node.js operates on the concept of local scope for each module, meaning variables defined within a module do not automatically become global unless explicitly exported. One question that arises is where a variable declared in a module file belongs in term ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

Extracting the JQuery library from its source code

Is there a simple method for extracting only the necessary functions from the jQuery library? I have found that many of the functions within the library are not being utilized, so it would be beneficial to remove them. ...

What is the method to retrieve JSON data from a URL and showcase the content on a JavaScript page?

I am currently developing a custom MS Teams application and I am facing an issue with fetching JSON data from a URL to display its contents later. Unfortunately, the fetch operation is failing. My objective is to retrieve a list of data from a specified UR ...

Error: Chrome is preventing an AJAX request

Hello everyone, I have been facing an interesting issue with my Ajax request. It seems to work perfectly fine in Internet Explorer, which is quite surprising. However, when I attempt to run the same code in Chrome, I encounter the following error: XMLHt ...

Tips for adjusting column sizes in react-mui's DataGrid based on screen size

I would like the title column to occupy 3/4 of the full row width and the amount column to take up 1/4 of the full row width on all screens sizes (md, sx...). Here is the updated code snippet: import React from 'react' const MyComponent = () =&g ...

Uploading a file using AngularJs

When it comes to uploading an image or file using HTML tag in AngularJS, it seems that the tag is not supported. The solution? Create a custom directive. In my index.html page, I included the following code: <body ng-controller="myController"> ...

Displaying a dynamic flag icon in a span element based on the selection from a mat-select

I am working on a mat-select component and I want to dynamically change a flag icon inside a span element in the mat-label based on the selected option. Currently, the initial flag is displayed correctly, but when I click on a different option, the flag d ...

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...

Combining two arrays in JavaScript and saving the result as an XLS file

I have a question that I couldn't find an answer to. I need to merge two arrays and export them to an Excel file using only JavaScript/jQuery. Let's say we have two arrays: Array 1 : ["Item 1", "Item 2"] Array 2 : ["Item 3", "Item 4"] When the ...

Utilizing Next.js for dynamic routing with [[...slug.js]] allows for comprehensive URL handling and seamless 404 page display for links leading back to the homepage - a feature

In order to achieve a single dynamic route for handling all requests in this application, I have created a file called [[...slug]].js. Data loading is managed using getServerSideProps(), allowing for server-side rendering. Notably, there are no index.js fi ...

Click to move directly to a specific section

This question may be common, but despite my research efforts, I have been unable to find a solution. I want to issue a disclaimer that I am new to javascript and jQuery. Here is an overview of what I am trying to achieve: I want two images that, when cli ...

Avoiding leaps through the use of dynamic pictures?

Currently, I am implementing the picture element along with srcset to download the same image but in varying resolutions depending on the screen size of the device. The image has a style of max-width: 100%, causing it to shift the content below when downl ...

In AngularJs, use ng repeat and ng switch to dynamically generate and display tables

I need help rendering a table with two columns using angularjs directives. <table> <tr ng-repeat="message in messages" > <td ng-switch-on="message.network" ng-switch when="twitter" ng-controller="TweetController"> <span> ...

Transform the image data retrieved from an external API into the appropriate format for displaying on the webpage

When I make a call to an external API, it returns image data that I want to render on my page. However, the response looks like this when I log it to the console: https://i.stack.imgur.com/GpDhH.png I'm not very familiar with image formats, so I&ap ...

The error message states: "Cannot create element as the React object is not

Recently delving into the world of React and Material UI, I've been working on creating an AppBar with nested Tabs. Here's a snippet of my current approach: import {React, PropTypes, Component} from 'react'; import TodoTextInput from & ...

Improve the looping mechanism to efficiently extract key values from an object and store them in an array

I am working with an object that contains various questions, each with a different difficulty level indicated by the "difficulty" property. I have implemented a for loop to sort the questions into categories based on their relative difficulty, such as easy ...

What could be the reason for one function returning undefined from identical API calls while the other functions produce successful results?

As I delved into incorporating the TMDB API into my project, a perplexing issue arose that has left me stumped. Despite utilizing identical code snippets in two separate files and functions, one of them returns undefined while the other functions flawlessl ...