The angular controller erroneously indicates that the modal form is valid even though it is not

I am currently working with a form that appears in a modal directive using bootstrap UI. The form consists of 2 input fields with html5 validation set to "required."

Initially, in the controller, I tried to check if the form is valid before proceeding to submit it to the server. However, I encountered scope-related issues when attempting to reference $scope.FormName.$valid. Eventually, I found a workaround by passing the form name through ng-click.

Despite this solution, I noticed that the controller code always shows the form as valid, even when the required fields are empty. I am now looking for a way to implement a check to ensure the form is truly valid before submission.

Below is the code snippet:

HTML Form:

 <form name="EmailForm"> 
    <div class="row">
        <div class="col-md-1 lbl_hdr">
            date:
        </div>
        <div class="col-md-1">
            {{Curr_Date  | date:'dd/MM/yyyy'}}
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-1">
                </div>
            </div>
            <div class="row">
                <div class="col-md-1 lbl_hdr">
                    from:
                </div>
                <div class="col-md-1">
                    <input type="email" required placeholder="email" />
                    <br />
                    <br />
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 lbl_hdr">
                    message:
                </div>
            </div>
            <div class="row">
                <div class="col-md-1">
                    <textarea class="msg_text" required rows="5"></textarea>
                </div>
            </div>
            <div class="row">
                <div class="col-md-9">
                    <button type="submit" ng-click="SendEmail(EmailForm)" class="btn btn-primary btn_padded_top">send</button>
                    <button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
                </div>
            </div>

        </div>
    </div>
</form>

Controller:

        $scope.openModal = function () {
        var modalInstance = $modal.open({
            templateUrl: '/js/app/templates/msg_modal.html',
            controller: function ($scope) {
                $scope.Curr_Date = new Date();

                $scope.SendEmail = function (EmailForm) {
                    if (EmailForm.$valid) {
                        EmailService.sendEmail("sdsd").success(
                            function (data) {
                            });
                    }//if valid
                };
            },
            size: size
        });
    };

The issue of "if (EmailForm.$valid)" constantly evaluating to true persists.

Answer №1

My issue was identical, but it was resolved by ensuring that all form elements had the ng-model attribute for AngularJS validation to work properly.

Simply include the attribute in all elements, like so:

<input type="email" required placeholder="email" ng-model="email" />

Answer №2

Consider utilizing the ng-submit directive and passing EmailForm.$valid as an argument.

<form name="EmailForm" ng-submit="SendEmail(EmailForm.$valid)"> 
    <div class="row">
        <div class="col-md-1 lbl_hdr">
            date:
        </div>
        <div class="col-md-1">
            {{Curr_Date  | date:'dd/MM/yyyy'}}
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="row">
                <div class="col-md-1">
                </div>
            </div>
            <div class="row">
                <div class="col-md-1 lbl_hdr">
                    from:
                </div>
                <div class="col-md-1">
                    <input type="email" required placeholder="email" />
                    <br />
                    <br />
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 lbl_hdr">
                    message:
                </div>
            </div>
            <div class="row">
                <div class="col-md-1">
                    <textarea class="msg_text" required rows="5"></textarea>
                </div>
            </div>
            <div class="row">
                <div class="col-md-9">
                    <button type="submit" class="btn btn-primary btn_padded_top">send</button>
                    <button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
                </div>
            </div>

        </div>
    </div>
</form> 

Next:

$scope.openModal = function () {
var modalInstance = $modal.open({
    templateUrl: '/js/app/templates/msg_modal.html',
    controller: function ($scope) {
        $scope.Curr_Date = new Date();

        $scope.SendEmail = function (isValid) {
            if (isValid) {
                EmailService.sendEmail("sdsd").success(
                    function (data) {
                    });
            }//if valid
        };
    },
    size: size
});

};

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

The feature to Select/DeSelect All does not function properly when dealing with individual records

Here's the JavaScript code I'm working with: if (document.forms[0].Check_All.value=="Select All") { for (i = 0; i < chk.length; i++) { chk[i].checked = true; document.forms[0].Check_All.value = "DeSel ...

What is the process for accessing and utilizing the value returned by a promise in a separate file?

I have developed a small project to demonstrate an issue. There are a total of 5 files in this project: - A container file that includes all the dependency injections. - A service file containing the necessary functions to be executed. - A controller fil ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

Cancel an AJAX request without interfering with the subsequent request

When working with a number input and the "onChange" event, I have come across an issue with my ajax request. Upon aborting the request, it seems to have a negative impact on subsequent requests. If I send just one request without aborting, everything runs ...

Having trouble running the d3js example on Ionic 2

I am having trouble running the example provided in this link: https://github.com/abritopach/ionic2-d3js-example Even after installing the latest Ionic 2 version and npm, I encounter an error when trying to run the app, as shown in the browser console. p ...

Creating Your Own Image Hosting Website: Learn how to consistently display an HTML file with a specific image from the URL

I'm currently in the process of developing my own image hosting site at Everything is functioning as intended, but I am looking to make a change. Currently, when a shared image link is opened, it only displays the image. However, I would like it to ...

What are some ways to modify attributes in a jQuery datatable?

Upon loading the page, I initially set serverside to false. However, under certain conditions, I need to change serverside to true without altering any other attributes. For example: $(tableID).DataTable({ serverSide : false; }); Changing it to: $(t ...

Issue encountered with create-next-app during server launch

Encountering an error when attempting to boot immediately after using create-next-app. Opted for typescript with eslint, but still facing issues. Attempted without typescript, updated create-next-app, and reinstalled dependencies - unfortunately, the prob ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...

The transitions in Vue do not seem to be functioning properly when used with router-link and $router

I have the following structure in my App.vue file: <script setup> import { RouterView } from "vue-router"; </script> <template> <RouterView v-slot="{ Component }"> <transition :name="fade" mod ...

A step-by-step guide on configuring data for aria's autocomplete feature

Currently, I am implementing aria autocomplete and facing an issue while trying to populate data from the server into the selection of aria autocomplete. I have tried setting the selected property of the aria autocomplete object, but it doesn't seem t ...

Guide on entering text into a concealed text box using WebDriver and Java

When attempting to use sendkeys on an input field, I encountered a warning that puzzled me: org.openqa.selenium.InvalidElementStateException: Element must not be hidden, disabled or read-only (WARNING: The server did not provide any stacktrace informati ...

How to eliminate the initial class with jQuery

I am encountering some issues with removing a class using jQuery. When I open a modal in Bootstrap, it generates code like this: <div class="modal-backdrop fade in"> in the footer. However, when I open a modal within another modal (2 modals), ther ...

Having trouble getting @vercel/ncc to work, keeps throwing a "Module not found" error

Recently, I have been attempting to follow a tutorial on creating custom GitHub actions using JavaScript from here. The tutorial suggests using the @vercel/ncc package to compile code into a single file if you prefer not to check in your node_modules folde ...

Exploring the mern.io scaffolder tool - Unraveling the essence of the .need method

While exploring the code of the scaffolder mern.io, I came across an intriguing method called ".need". It appeared to be related to es6 classes, but unfortunately, I couldn't find any valuable information about it. Thus, I'm curious to know: what ...

Higher Order Component for JSX element - displaying JSX with wrapped component

I am looking to utilize a ReactJS HOC in order to implement a tooltip around JSX content. The function call should look similar to this: withTooltip(JSX, "very nice") To achieve this, I have created the following function: import React from "re ...

Ways to verify if an element includes a specific class in JavaScript

When the mouse hovers over each paragraph within the DIVs with the "change" class, the font color should turn red, and revert back to black when the mouse is not on them. Here's my current code: var paragraphs = document.getElementsByTagName('p& ...

Show blob file as a PDF document in a popup or dialog box using HTML and TypeScript

I am currently working on integrating TypeScript and HTML to showcase the result of a webservice call as a PDF in a popup/dialog within the same page. While I can successfully open the PDF in a new tab using the window.open(url) method, I'm encounter ...

Creating a Javascript Regular Expression to detect both accented and non-accented variations of a given string

Is there a way to use regular expressions in JavaScript to match both accented and non-accented versions of a string? I am customizing jQuery-ui's autocomplete feature by adding bold HTML tags around words in the suggestions. Here is my code snippet: ...

Issue encountered when attempting to invoke a PHP function using Javascript through AJAX

I'm currently working on incorporating a PHP function into my HTML file using Ajax (which also contains JavaScript). My goal is to retrieve all locally stored JSON files. I've been following a guide at , but I'm facing some challenges. When ...