The art of validating data in Angular.js

I need assistance with my form that looks like the following:

    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h4 class="nomargin">Let us know your concern or question and we will try to respond within 24 hours.</h4>
</div>
<div class="modal-body paddingmodal2">
    <form id="support-form" name="supportForm"  class="nobottommargin" novalidate="">
      <div class="col_full">
            <label for="login-form-username">Description <small>*</small></label>
            <textarea rows="4" cols="50" type="text"  ng-class="{'error': submitted && supportForm.description.$error.required}" id="login-form-username" name="username" class="sm-form-control" ng-model = 'support.description' required/>
        </div>
        <div class="alert" role="alert" ng-class="{'alert-danger':!isLoginSuccess, 'alert-success':isLoginSuccess}" ng-show="isShowLoginAlert" ng-bind="loginSubmitStatusMsg"></div>
        <div class="col_full nobottommargin no-margin-col-full">
            <button type="submit" class="button button-3d button-black nomargin col_full" id="login-form-submit" name="submit-bt" ng-click="saveSupportData(supportForm,support)" ng-disabled="isDisableLoginBtn">Submit</button>
        </div>

    </form>
</div>

JavaScript:

$scope.saveSupportData = function(supportForm,data){
                 if(supportForm.$invalid){
                    return;
                }
}

After clicking on the button, the text area border should be highlighted, but this is not currently happening. Can anyone provide some guidance?

Answer №1

A form is an instance of FormController. When a form instance is created, it can optionally be added to the scope using the name attribute.

Similarly, an input control with the ngModel directive contains an NgModelController instance. This control instance can be linked as a property of the form instance by specifying the name attribute on the input element. The name attribute determines the property name on the form instance.

This means that the internal states of both the form and the control are accessible for binding in the view through standard binding methods.

These capabilities allow us to enhance the example above with the following features:

Displaying custom error messages when a user interacts with a control (when $touched is true) and displaying custom error messages upon form submission ($submitted is true), even if the user has not interacted with a control

The suggested code should look like this:

ng-class="{'error': submitted && supportForm.username.$error.required}"

Make sure to replace 'username' with your actual field name. The 'submitted' variable should be set to true when the form is submitted. You can try implementing it using the function below:

$scope.saveSupportData = function(supportForm,data){
    $scope.submitted=true;
     if(supportForm.$invalid){
      return;
   }
}

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

Off Canvas left navigation menu using Bootstrap

I am working on creating a responsive layout for a webpage using Bootstrap. On larger displays, such as desktop resolutions, I want the webpage to show the header and left navigation as normal. However, when the site is resized to that of tablets or mobile ...

What is the reason skip does not function properly at the start of the aggregation pipeline, yet performs as expected at the conclusion of it?

Initially, the skip stage in this MongoDB database aggregation framework pipeline isn't functioning as expected: [ { $skip: (!offset)? 0 :(offset-1)*limit }, { $match: (query)? query : {} } , { $lookup: ..., ...

Storing a value from an external JavaScript variable into an HTML variable involves a few key steps

Is there a way to transfer the jQuery variable value to an HTML variable? Take a look at my code, This is the JavaScript function that resides in an external script function createImage(settings) { var kk = createCanvas(settings)[0].toDataURL(' ...

Locate and eliminate all occurrences of "<br />" within a webpage using jQuery

I am currently working on a project using the Cargo Collective platform and I have noticed that it automatically includes unnecessary <br /> tags in the body of my document. Is there a way to use jQuery to scan for all instances of <br /> tags ...

Autocomplete like Google with arrow key functionality

I have developed a basic search engine that retrieves data from a MySQL database using the PHP "LIKE" function (code provided below). Everything is functioning correctly, but I would like to enhance it so that users can navigate search results with arrow k ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...

Database query failing to make any changes

Currently, I am facing an issue where I am attempting to update a value in a table based on a specific condition being met, but for some reason the update is not taking place: if (req.headers['user-agent'].includes('HeadlessChrome') ...

How to use Node JS to interact with audio devices

I am looking for a way to stream audio from my Focusrite Saffire audio interface to my Node.js server. I have considered accessing the audio interface through the browser using HTML5, similar to capturing microphone output with getUserMedia. However, I c ...

The issue of "No 'Access-Control-Allow-Origin' header" can arise when working with AngularJS, Nginx

I have researched various versions of this question and reviewed all related discussions on SO and Google. My goal is to send a cross-domain POST request from an angularJS app to an nginx server. While GET requests work fine, the POST request is not funct ...

How can you ensure that an event is added only once when using mouseover functionality?

One approach involves utilizing an event listener that operates as follows (in pseudo code): canvas.onmousemove = function (e) { checkCollision(e); }; var checkCollision = function(e){ var context = canvas.getContext('2d'); var coordina ...

How can MongoDB be used to sort a nested array using the push method?

Here is a query to consider: EightWeekGamePlan.aggregate( [ { $group: { _id: { LeadId: "$LeadId", BusinessName: "$BusinessName", PhoneNumberMasque: "$PhoneNumberMasque", ...

iterative string ng-list that is specified in the text $scope variable

Is there a way to set up a dynamic ng-repeat in $scope variable that looks like this: $scope.radioOptions =[{value:1,name:'radio1'},{value:2,name:'radio2'}]; $scope.item = { model: "radio", radioOptions:'opt in radioOptio ...

How to programmatically update a specific field in a Firestore document using Angular without manually specifying the field key

Is there a way to update a document inside Firestore without explicitly specifying the field to be updated in the code? Suppose the HTML tag in Angular already provides both the key and the import value that needs to be updated: HTML Tags <form ...

html/css - techniques for transitioning a centered image on a landing page into a navbar logo when scrolling

Creating a minimalist navbar without the use of JavaScript or custom CSS is easier than you think. <nav class="navbar navbar-expand-md navbar-light bg-faded"> <a class="navbar-brand" href="#"> <img src=&qu ...

Guidelines on receiving a user's color input and showcasing it with JavaScript

/* Take a color input from the user and apply it to the variable called "message". */ <script type="text/javascript"> var textcol, message = "Great choice of color!"; textcol=window.prompt("Please enter a color:&quo ...

What is the best way to define a local variable with specific filters assigned to it?

I am working with an ng-repeat directive in the following manner: item in items | filter:myFilter | page:currentPage My goal is to determine the current count of items after applying the myFilter filter for pagination purposes. However, I found that foll ...

What is the process of unmounting the next/script on page change within a next.js application?

Is there a way to load a script only on specific pages? Next.js suggests using next/script tag for this purpose. However, I noticed that even when navigating to different pages, the script remains visible at the end of the HTML body. https://i.sstatic.net ...

Generating a dynamic clickable div using Angular 6

How can I create a user-friendly interface that displays an image with clickable divs around detected faces, allowing users to view specific attributes for each face? I'm looking for a solution where I can have divs or buttons around each face that t ...

Guide to updating user input on the screen when a click event occurs using Javascript and HTML

I've been working on writing HTML and JavaScript code that enables user input to change based on which button the user clicks. The idea is that the user enters find/replace values, and when they hit the replace button, the text they initially entered ...

Changing text and applying a different span class using a Jquery button toggle

My current issue involves a functional toggle button that smoothly slides a div up and down. However, I am facing problems when attempting to change the toggle button status: You can view a demonstration of my code here: http://jsfiddle.net/zwu0sn83/3/ B ...