Error: AngularJS form validation is not working properly

I've been following the AngularJS documentation, but I'm having trouble with my validations. The error messages are not showing up and the minimum length restrictions for the form fields are not working:

<form name="callbackForm" ng-submit="requestCallback()"> 
  <div class="col-md-3">
    <input name="name" type="text" class="form-control" placeholder="Name..." ng-model="callback.name" ng-minlength="3" required=""/>
  </div>
  <div class="col-md-3">
    <input name="telephone" type="text" class="form-control" placeholder="Telephone..." ng-model="callback.telephone" ng-minlength="11" required=""/>
  </div>
  <div class="col-md-3">
    <input type="submit" class="btn btn-sm btn-block" value="Call Me!">
  </div>
  <div class="col-md-3">
    <p ng-show="callbackForm.name.$error.required" class="help-block">Your name is required.</p>
    <p ng-show="callbackForm.telephone.$invalid && !callbackForm.telephone.$pristine" class="help-block">Your telephone number is required.</p>
  </div>
</form>

This is my controller:

'use strict';
app.controller('footerController', ['$scope', '$http', function ($scope, $http) {

    $scope.requestCallback = function () {

        alert("form callback");

    };
}]);

But for some reason, my error messages won't display and the ng-minlength validation isn't preventing form submission. What could be causing this issue?

Answer №1

It appears that your code is functioning correctly.

If you encounter submission restrictions on error, you must explicitly utilize Angular's validation feature by implementing something like this:

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

Below is a snippet:

function Ctrl($scope) {
  $scope.requestCallback = function() {
    alert("form callback");
  };
}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>

<div ng-app>
  <div ng-controller="Ctrl">
    <form name="callbackForm" novalidate ng-submit="callbackForm.$valid && requestCallback()">
      <div class="col-md-3">
        <input name="name" type="text" class="form-control" placeholder="Name..." ng-model="callback.name" ng-minlength="3" required="" />
      </div>
      <div class="col-md-3">
        <input name="telephone" type="text" class="form-control" placeholder="Telephone..." ng-model="callback.telephone" ng-minlength="11" required="" />
      </div>
      <div class="col-md-3">
        <input type="submit" class="btn btn-sm btn-block" value="Call Me!">
      </div>
      <div class="col-md-3">
        <p ng-show="callbackForm.name.$error.required" style="font-size: 14px; color:#ff0033" >Your name is required.</p>
        <p ng-show="callbackForm.name.$error.minlength" style="font-size: 14px; color:#ff0033" >Your name should have at least 3 letters</p>
        <p ng-show="callbackForm.telephone.$error.required" style="font-size: 14px; color:#ff0033" >Your telephone number is required.</p>
        <p ng-show="callbackForm.telephone.$error.minlength" style="font-size: 14px; color:#ff0033" >Your telephone number should have at least 11 numbers.</p>
      </div>
    </form>
  </div>
</div>

Answer №2

Form validation is in progress. To utilize the requestCallback() function, ensure that your form is connected to the controller.

Enclose your form within a controller using ng-controller

<div ng-controller="footerController">

<form name="callbackForm" ng-submit="requestCallback()"> 
                <div class="col-md-3">
                    <input name="name" type="text" class="form-control" placeholder="Name..." ng-model="callback.name" ng-minlength="3" required=""/>
                </div>
                <div class="col-md-3">
                    <input name="telephone" type="text" class="form-control" placeholder="Telephone..." ng-model="callback.telephone" ng-minlength="11" required=""/>
                </div>
                <div class="col-md-3">
                    <input type="submit" class="btn btn-sm btn-block" value="Call Me!">
                </div>
                <div class="col-md-3">
                    <p ng-show="callbackForm.name.$error.required"  || callbackForm.name.$error.minlength class="help-block">Your name is required.</p>
                    <p ng-show="callbackForm.telephone.$invalid && !callbackForm.telephone.$pristine" class="help-block">Your telephone number is required.</p>
                </div>
            </form>

</div>

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

What sets apart a class from a service in NativeScript?

I am embarking on the journey of learning Nativescript + Angular2, and while reading through the tutorial, I came across this interesting snippet: We’ll build this functionality as an Angular service, which is Angular’s mechanism for reusable classes ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

Executing Scripts within the Browser: A Guide to Using Selenium

One of my current objectives involves running a script on my Selenium browser that establishes a variable and then using DevTools to access this variable in the console log. Below is the conflicting script that I am encountering issues with: from selenium ...

Error: res.send is not a valid method in Node.js

I am encountering an issue with the code below, specifically receiving an error stating "res.send is not a function". I would appreciate any assistance. Code Snippet: var http = require('http'); var fs = require('fs'); var connect = ...

Using arrays as props in React with Typescript

In my code, I have a Navbar component that contains a NavDropdown component. I want to pass an array as a prop to the NavDropdown component in order to display its dropdown items. The array will be structured like this: DropDownItems: [ { ...

The JSX in React won't display the modified state on the user interface

In my diary object, I have records of 2 meals function Magicdiary() { const [diary, setDiary] = React.useState<MagicDiaryDay[]>([ { mealName: "Breakfast", ingredient: null }, { mealName: "Lunch", ingredient: null }, ]) ...

VueJS - Create a dynamic timer using setInterval function

I have a function that is initially triggered within the 'mounted' lifecycle hook, and then it continues to be called every 15 minutes. In my component, I am looking to showcase a countdown until the next setInterval in minutes and seconds. asyn ...

How can we efficiently load a JSON file from a local path into an HTML document in a way that is compatible with all browsers?

I am attempting to retrieve JSON data from a local path and display it on a basic HTML page. I have tried various methods such as fetch, ajax in order to load the data and update the corresponding values on the web page. The goal is to host this page so t ...

Encountering the WRONG_DOCUMENT_ERR: DOM Exception 4 error when attempting to close Fancybox after making edits in inline Tiny

I am encountering a problem with my fancybox that includes a form for collecting user input, which features a tinyMCE editor. When trying to close the fancybox after making substantial edits in the TinyMCE, whether by clicking the close X or submitting the ...

The scrollIntoView function is not functioning as expected

Having an issue with my function called scrollIntoView. It just refuses to work :( Take a look at the code below: HTML <section class="page_mission"> <div class="page_mission_text"> <div class="scroll-animations"> <di ...

Listening for events on an array of elements using jQuery

My task involves populating an array with elements using the .each() method and the $(this) selector. (function($){ var elements = new Array(); var index = 0; $("img").each(function() { if($(this).attr("attribute")){ $(thi ...

Having trouble selecting a radio button in React JS because it's marked as read-only due to the check attribute

In my scenario, I have a child component with radio buttons. The questions and radio buttons are populated based on the data, with each set consisting of one "yes" and one "no" option. I am attempting to automatically check all radio buttons that have a v ...

More efficient methods for handling dates in JavaScript

I need help with a form that requires the user to input both a start date and an end date. I then need to calculate the status of these dates for display on the UI: If the dates are in the past, the status should be "DONE" If the dates are in the future, ...

Load information from a database into an array using Angular, PHP, and MySQL

I am currently developing a simple to-do application that utilizes Angular for the front end and PHP/MySQL for the backend. As of now, the app allows users to add new tasks and track the "percentage completed" daily, which is then stored in the database u ...

Discovering the vacant fields within a database by looping through them

My goal is to download a .pdf document from the external database Contentful by utilizing an HTML link on a user interface. The issue arises when certain fields inside Contentful do not always necessitate a pdf document. In these cases, the field remains ...

Navigating Modal Pop-ups in Django

My current approach for handling modal windows involves referring to this article here. However, I am struggling with implementing some basic functionality using this method. Within my HTML code, I have the following structure: {% for order in queryset% ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

A method to eliminate the mouse-over effect following the selection of an input box

Currently, I am utilizing Angular and encountering three specific requirements. Initially, there is an input box where I aim to display a placeholder upon pageload as 'TEXT1'. This placeholder should then toggle on mouse hover to display 'TE ...

How can one decrease the size of a React project?

After running npx create-react-app my-app, the download was quick but then it took over an hour for the installation process to complete. Upon checking the size of the newly installed project, I found that the node_modules folder alone was a whopping 4.24 ...

Switch content based on value with Javascript

One of my elements is: <a href="#" type="link" class="button send" classAct="button send" classSel="button send pressed" label="encrypt" title="sendmessage" onclick="add_encryption();">Encrypt</a> When toggled via the JavaScript below, I want ...