Wait until the user submits the form before activating Angular validations, and do not display any validation messages if the user deletes text from a text box

I am looking to implement angular validations that are only triggered after the user clicks on submit. I want the validations to remain hidden if the user removes text from a textbox after submitting it. Here is what I need: - Validations should not be displayed when user initially enters text - Display validations only after user clicks on submit - If user interacts with or removes text from the textbox after submitting, validation messages should not show

Could you please provide a solution for this? Quick responses are appreciated. I would be extremely grateful if you could also include fiddles in your response.

Thank you in advance.

Answer №1

To tackle this issue, consider utilizing a flag approach. Let's say you have a form with an input field. When the submit button is clicked, set the isSubmitted flag to true. Conversely, when the input field changes, set it to false. Then display your validation message based on the value of this flag. Here's a theoretical controller example:

function myController($scope) {
  $scope.isSubmitted = false;

  $scope.submitForm = function() {
    $scope.isSubmitted = true;
    // Perform other actions here...
  }

  $scope.inputChanged = function() {
    $scope.isSubmitted = false;
  }
}

Incorporate this logic into your view:

<input name="inputField" type="text" ng-model="myModel" ng-change="inputChanged()" required="" />
<span ng-show="form.$error.required && form.$dirty && isSubmitted">Please enter a valid name</span>

Answer №2

If you're unsure about what you need, take a look at this code snippet which may come in handy.

Here we have a basic form along with its controller and some fields that are validated. In this example, each field is mandatory but no feedback on validation is provided to the user.

The form passes validation only if it's deemed valid and then the submission is recorded with a flag (true/false). If the flag is set to true and the user interacts with any of the fields, all fields are reset.

The Controller

(function(){


    var Controller = function($scope){

        // Parameters
        var isFormSubmitted = false;

        // Methods

        // Shared Methods
        $scope.checkFocus = function(){

            if(!isFormSubmitted){ 
                return;
            }

            // Reset all fields
            $scope.fields = null;

            // Do something

        }

        $scope.validate = function(){

            isFormSubmitted = true;

            // Perform validation here

        };

    };

    Controller.$inject = [
        '$scope'
    ];

    app.controller('MainCtrl', Controller);


})();

The view

<div ng-controller="MainCtrl">


   <form name="form" ng-submit="form.$valid && validate()" novalidate>

        <input ng-focus="checkFocus()" ng-model="fields.username" type="text" required placeholder="Username">
        <input ng-focus="checkFocus()" ng-model="fields.password" type="password" required placeholder="Password">
        <input type="submit" value="Submit">

   </form>


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

Ways to append each list item from one unordered list to the end of another based on their unique styles

I am in the process of making a website responsive and I am faced with the task of combining two different menus. In order to achieve this, I need to transfer all list items (li) from one unordered list (ul) to another. Provided below is a simplified vers ...

Issues with running grunt serve

I'm encountering issues with running my project in WebStorm IDE. When I enter grunt serve, I am faced with the following errors: grunt serve Loading "connect.js" tasks...ERROR >> SyntaxError: C:\Users\TT\Documents\ES\fr ...

How can I replace any non-alphanumeric characters in a string with an underscore using JavaScript or TypeScript?

There is a unique string generated from an external data source that I cannot manage. The system above me necessitates the IDs to adhere to this rule: "Field names should start with a letter and can solely consist of letters, numbers, or underscores (&apos ...

What is the best way to redirect a user to a different URL in Express while also sending additional data along with the request

[NODE, express] Developing a Facebook application where user grants access and is redirected to my site with a unique code at abc.com/heyBuddy/fb/callback?code="adasdasdasda". Once the code is received in route router.get('/heyBuddy/fb/callback', ...

Trouble with uploading images through multer is causing issues

When setting up multer, I followed this configuration let multer = require('multer'); let apiRoutes = express.Router(); let UPLOAD_PATH = '../uploads'; let storage = multer.diskStorage({ destination: (req, file, cb) => { ...

Unable to load JSON information into an ExtJS grid

I have exhausted all the solutions I found (there are many on Stackoverflow) in an attempt to fix my extjs store issue. Despite ensuring that the grid is displayed correctly, the data still refuses to show up. Feeling perplexed, I am sharing the "store" co ...

Exploring ways to integrate Javascript and CSS into a Bootstrap lightbox modal dialog?

Can someone help me figure out how to use the bootstrap lightbox to display a form with specific CSS style and JavaScript code for the form? I'm having some trouble implementing it. I specifically need this setup because I am using Selectize.JS to cr ...

AngularJS shows an error when attempting to access the property 'childNodes' of an undefined element

Recently diving into AngularJS, I incorporated bootstrap validator to ensure form validation in my project. Initially, everything was running smoothly until I introduced the following snippet into my controller's JavaScript file for validation: $(doc ...

What is the method for storing API status JSON in the state?

Can anyone help me figure out why the json in the register state is returning an empty object after console.log(register); from that state? import React, { useEffect, useState } from "react"; import { Formik } from "formik"; // * icons ...

Using the filter function in JavaScript to retrieve specific data

When the user_id from two different data sources matches, I need to return the email from the first source. The first source is a table in PostgreSQL called "results" and the second source is JSON data. I attempted this code snippet: var table = db.query ...

Tips for passing data to a child component from a computed property

Currently in the process of setting up a filter using vue-multiselect. Everything seems to be working fine, but there's one issue I can't seem to resolve. Upon page reload, the label (v-model) appears empty. The root cause seems to be that the v ...

Develop a JSON structure by retrieving nested documents using Firebase Firestore and Express

I'm currently working on developing an application using Express and Firebase Cloud Functions. I'm facing a challenge in creating a nested JSON structure based on the database schema specified below: Below is the code snippet that I am using: ex ...

Apologies, but it seems there was an issue reading the "checked" property as it is null

I am currently facing an issue with the submit button in my Django application. It appears that the Javascript function is unable to determine which checkboxes are checked, as all I see in the console logs are "cannot read properties of null, reading "chec ...

Difficulties encountered while attempting to modify a class using Javascript

Recently, I've encountered an issue with my JavaScript where I am unable to keep a particular element's class changed. Despite attempting to change the class to "overlist", it only stays that way briefly before switching back to its original stat ...

Loading indicator for buttons

Issue with submit button onclick function (onClick="mandatoryNotes()"). It is taking a while to load, so a preloader script was added. The preloader is now working, but the function is not being called. Seeking assistance. Thank you. function mandatoryN ...

Is it time to advance to the next input field when reaching the maxLength?

In my Vue form, I have designed a combined input field for entering a phone number for styling purposes. The issue I am facing is that the user needs to press the tab key to move to the next input field of the phone number. Is there a way to automaticall ...

Utilizing PNG images with color in CSS, HTML, or JavaScript

On my website, I have an image in PNG format. I am wondering if there is a way to change the color of the image using HTML5, JavaScript, or CSS. Ideally, I would like the image to be changed to white by inverting its colors (changing black to white, not al ...

In the console, a JSON string is displayed, however the PHP variable outputs as null

Below is the snippet of javascript code I am working with: $('.showEditForm').click(function () { var webpagefileID = this.id; if($('#editForm').css('display', 'none')) { $('#editForm').css ...

Is there a way to simultaneously apply the :active pseudoclass to multiple elements?

<div id="a">A</div> <div id="b">B</div> <div id="c">C</div> <style> #a, #b, #c { height: 100px; width: 100px; background-color:red; font-size: 100px; margin-bottom: 20px; } ...

Navigate through FAQ items with sliders using Owl Carousel 2 - Easily switch between different chapters

Exploring the creation of a FAQ section with individual carousels for each item. My primary objective is for the carousel to transition to the next chapter when advancing beyond the last slide (backwards navigation would be a future enhancement). I'v ...