Using an AngularJs directive to perform form validation on an input field

Currently, I am working on a project where there are multiple submit forms with similar fields. To streamline the process, I have made the decision to transfer some fields to directives.

Here is an example of the form:

<div loading class="col-sm-12" ng-controller="Controller">
        <form name="myForm" role="form" novalidate>
            <fieldset class="lines-header-border">
                <div class="col-sm-6">
                   <div class="form-group">
                       <label class="col-sm-4 control-label">Date</label>
                       <div class="col-sm-7">
                            <date-field 
                             model="myModel" 
                             date-picker-options="datePickerOptions"
                             for-name="date"
                             for-ng-class="myForm.date.$invalid"
                             is-required="true"/>

                       </div>
                     <div class="col-sm-4">
                    <input class="form-control" 
                           name="amount" 
                           ng-model="amount" 
                           ng-class="{ 'has-error' : myForm.amount.$invalid }" 
                           required/>
                </div>
                    </div>
            </fieldset>
        </form>
    </div>

Date field directive implementation:

.directive('dateField', function() {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            model: '=',
            datePickerOptions: '=',
            isRequired: '@',
            forName:'@',
            forNgClass: '&'
        },
    template: '<input ui-date="datePickerOptions" type="date" name="{{forName}}" class="form-control"  ng-model="model" ng-class="{ \'has-error\' : forNgClass()}"  ng-required="isRequired"/>'
    };
});

Issue with validation during form submission: While other fields are being validated correctly upon form submission, the date field does not seem to be validating. I suspect that the problem lies in

for-ng-class="myForm.date.$invalid"
.

Any suggestions on how to address this issue?

Answer №1

If you need to access the controller scope variable "myForm.date.$invalid" using the directive attribute "for-ng-class", you can set "@" for the directive scope variable "forNgClass" to enable two-way data binding. This way, when the input field is changed, the class will be updated accordingly.

scope:{
    .....
    forNgClass: "@"
    .....
}

I have created a simple example:

UPDATE: Angular cannot dynamically generate the name attributes of input elements. Therefore, we need to wrap the input element of dateField in an inner form (using the ngForm directive). For more information about nested forms in Angular, you can check the Angular documentation.

<!DOCTYPE html>
<html>

<head>
    <style>
        .has-error{
            background:#ccc;
            border: 1px solid red;
        }
    </style>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.11/angular.min.js"></script>
    <script src="angular-ui-date.js"></script>
</head>

<body ng-app="MyApp">
    <div ng-controller="MyCtrl">
        <form name="myForm" novalidate>
            <h2>Selected date: {{dateData}}</h2>
            <date-field model="dateData" is-required="true"></date-field>
            <date-field model="dateData2" is-required="true"></date-field>
            <h3>myForm is invalid?</h3>{{myForm.$invalid}}
        </form>
    </div>
    <script>
        angular.module("MyApp",['ui.date'])
        .controller("MyCtrl",function($scope){

        })
        .directive("dateField",function(){
            return {
                restrict: "E",
                replace: "true",
                template: '<ng-form name="subForm"><input ui-date ui-date-format="yy-mm-dd" type="date" ng-class="{\'has-error\':subForm.myDate.$invalid}" name="myDate" ng-model="model" ng-required="isRequired"/></ng-form>',
                scope:{
                    model: "=",
                    isRequired: "@"
                }
            };
        });
    </script>
</body>

</html>

Here is an Online demo for reference.

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

AngularJS: The requested resource does not have the "Access-Control-Allow-Origin" header

Currently developing my web application using AngularJS, I have a file named script.js which contains the following code: var module = angular.module('project', ['ngRoute']); // setting up our routes module.config(function ($r ...

Using jQuery to target form elements that have a specific class assigned to them

I am facing an issue with targeting input fields within a specific form on a page. The form has a certain class, let's say "has-error," and I want to remove this class from all the input fields in that form. I attempted the following code snippet: t ...

A notification appears when the record is being inserted after clicking the button

Just venturing into the PHP and MYSQL realm, so please excuse any beginner questions. Before I submit data from a form to my SQL table, I'd like to display a confirmation POP UP message asking "Are you sure you want to insert this data?" ...

Currently, I'm attempting to figure out a way to create a CSS string in my MVC ASP.NET project. Any ideas or suggestions are greatly appreciated

I am currently exploring solutions to generate a CSS string in my ASP.NET MVC Web Application. Specifically, I am interested in creating this at the selector level. For instance, I might have a class named "TableFormat" with the following CSS properties: ...

Exploring the process of generating multiple drop-down menu items in ASP.NET using AngularJS

I am currently working on a student registration form that includes two drop-down list boxes. The first box contains gender details, and the second one contains subject details. I am attempting to populate these items for the corresponding list boxes in ...

Using JavaScript to Establish Default Homepage in FireFox and Internet Explorer

How can I set a web address as the default homepage for a client? Specifically looking for solutions for (pageload) on IE8 and Firefox 3 (or newer versions). Thank you in advance for your help. Best regards ...

What is the best way to incorporate setTimeout in a loop using Coffeescript?

window.onload = -> boxOrig1 = 10 boxOrig2 = 30 canvasW = 400 canvasH = 300 ctx = $("#canvas")[0].getContext('2d'); draw = (origin,dimension) -> ctx.clearRect(0, 0, canvasW, canvasH) ctx.fillStyle = 'rgb(200,0 ...

Error: Attempted to submit an invalid or unexpected input token

I want to display my ship registration number from the database in an AJAX response. I am using a method to send my field and then show the ship registration number in another function. Here is the code snippet that I have debugged: show_name(2d1c9a71586 ...

Move information from one page to another

I'm currently using Ionic 2 and attempting to pass data from one page to another. Specifically, I want to transfer the data of a selected list item from the first page (quickSearch) to the second page (quickSearchDetail). To illustrate this, refer to ...

Include a single element repeatedly on a single webpage

Is there a way to add the same component multiple times on one page? I have an input component that receives props and performs certain functions. I need to include more than one instance of this input component on a single page, but when I try to copy and ...

The contents of a JSON Object will not be logged by Node, no matter the approach

I am currently encoding data for a Node.js WebSocket server in JSON format. When attempting to display the contents of the JSON object on the server side, I am encountering the issue where Node simply logs object Object I have experimented with the follow ...

Script for running a React app with Prettier and eslint in a looping fashion

My Create React App seems to be stuck in a compile loop, constantly repeating the process. Not only is this behavior unwanted, but it's also quite distracting. The constant compiling occurs when running the default npm run start command. I suspect t ...

Unable to invoke the setState function within the onSubmit handler of Formik

Every time I submit my form, I want to display an alert. I attempted to pass my state as a prop to the component, but it didn't work. Here's how my class state looks: this.state = { alert_variant: '', alert_heading: ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...

Steps for implementing target='_blank' on a <Link> tag with more than just an <a> element inside

I'm facing an issue where I need to open a new browser tab and redirect to a specific URL when a button is clicked. The problem arises when using an element other than an anchor tag inside the Next's <Link> element, as it seems to ignore th ...

Automatically scroll the page upon loading if the user is at the top of the page

Is there a way to trigger an action only when the page is detected to be at the very top, without executing it otherwise? I think maybe using an if statement could work, but I'm not entirely sure how to go about it. For instance, I'd like the pa ...

Strategies for injecting data into VueJS components after the page has fully loaded

My project utilizes Vue.js and Nuxt.js, and within the settings page, users can modify their personal settings. This single page allows users to navigate between tabs. <template> <div class="account-wrapper"> // Code content he ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...

Encountered an issue during Karma unit testing of an Ionic App: the error message [ng:areq] indicates that the argument 'StockCtrl' is not recognized as a function and is

I've encountered an issue while trying to conduct unit testing on my ionic app. Despite checking previous queries, none of the given solutions seem to work for me. Any suggestions on what might be causing this error? The error message I'm receiv ...

Each $.each function varies based on the type of object it is iterating

I have encountered an issue with my $.each statement. When it is written like this: $.each($(".permissions"), function (index, element) { ... }).promise().done(function () {...}); everything works fine. However, when I change the $.each statement to: ...