Challenges with validating forms in AngularJS

I've been attempting to implement a basic form validation using AngularJS, but for some reason it's not working as expected. I can't seem to figure out what I'm missing.

HTML Form Code

<form role="form" class="ng-pristine ng-valid" name="registerForm">
                        <fieldset>
                            <div class="form-group">
                                <input class="form-control" placeholder="First Name" name="firstname" type="text"
                                        autofocus="" required ng-class="{'has-error': registerForm.firstname.$invalid}">
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="Last Name" name="lastname" type="text" value="">
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="E-Mail" name="email" type="email" value="" ng-class="{'has-error': registerForm.email.$dirty}">
                                <div ng-show="registerForm.email.$dirty">Email Invalid</div>
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="Password" name="password" type="password" value="" autocomplete="off">
                            </div>
                            <div class="form-group">
                                <input class="form-control" placeholder="Organization Name" name="organizationName" type="text" value="">
                            </div>
                            <div class="form-group">
                                <select data-ng-options="item.Display for item in OrganizationTypes track by item.Value" data-ng-model="SelectOrganizationType" class="form-control">
                                    <option value="">-Select Organization Type-</option>
                                </select>
                            </div>
                           
                            <input type="button" value="Register" class="btn btn-lg btn-success btn-block" data-ng-click="Submit()" name="btnSubmit"/>
                           
                        </fieldset>
                    </form>

The problem lies in the fact that when I input an invalid email address, it fails to display the error message "Email Invalid" as expected.

Even when I try to debug the form before submitting with blank fields, it shows "registerForm.$valid = true". Any ideas on what could be causing this issue? Is there a specific module that needs to be included?

Check out the Plunker demo for reference.

Answer №1

To start, make sure that registerForm.email.$error.email triggers the alert for an 'invalid email'.

Next, consider binding these input fields with ng-model, although it may not be necessary.

Also, don't forget to include 'novalidate' in the form element.

 <div class="form-group">
      <input class="form-control" placeholder="E-Mail" name="email" type="email" value="" ng-model="" >
      <div ng-show="registerForm.email.$error.email">Email Invalid</div>
 </div>

Answer №2

You seem to be missing some crucial details. Firstly, it is essential to associate your fields with a model in order for validation to work correctly. Secondly, your method of accessing errors appears to be inaccurate.

Check out this functional plunkr that demonstrates what you are attempting to achieve.

Highlighted below is the pertinent code snippet:

<body ng-controller="MainCtrl">
  <form role="form" name="registerForm" novalidate>
    <fieldset>
      <div class="form-group">
        <input class="form-control" placeholder="First Name" name="firstname" ng-model="firstname" type="text" autofocus="" ng-class="{'has-error': registerForm.firstname.$error.required}" required />
      </div>
      <div class="form-group">
        <input class="form-control" placeholder="Last Name" name="lastname" ng-model="lastname" type="text" value="">
      </div>
      <div class="form-group">
        <input class="form-control" placeholder="E-Mail" name="email" ng-model="email" type="email" value="" ng-class="{'has-error': registerForm.email.$error.pattern}" ng-pattern="/^\S+@\S+\.\S+$/i" required />
      </div>
      <div class="form-group">
        <input class="form-control" placeholder="Password" name="password" ng-model="password" type="password" value="" autocomplete="off">
      </div>
      <div class="form-group">
        <input class="form-control" placeholder="Organization Name" name="organizationName" ng-model="organizationName" type="text" value="">
      </div>
      <div class="form-group">
        <select data-ng-options="item.Display for item in OrganizationTypes track by item.Value" data-ng-model="SelectOrganizationType" class="form-control">
          <option value="">-Select Organization Type-</option>
        </select>
      </div>

      <input type="button" value="Register" class="btn btn-lg btn-success btn-block" data-ng-click="Submit()" name="btnSubmit" />

    </fieldset>
  </form>

  <div ng-show="registerForm.firstname.$error.required">Please enter a first name.</div>
  <div ng-show="registerForm.email.$error.pattern || registerForm.email.$error.required">Invalid Email</div>

</body>

Answer №3

It seems that using $error with $dirty is necessary, for example:

<div ng-show="registerForm.email.$dirty && registerForm.email.$error.email">Email Invalid</div>

Additionally, remember to include novalidate in order to deactivate default browser validation:

<form role="form" class="ng-pristine ng-valid" name="registerForm" novalidate>

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

Restrict Vue Router access to specific pages only

Once a user has logged in for the first time, they are directed to the CreateProfile page where they can enter their profile information. I want to restrict access to this page so that if the user manually types the URL into their browser (e.g. www.myproje ...

It is generally not recommended to begin a constructor name with a lowercase letter in jsPDF

I'm attempting to generate a PDF using React const myComponent = () => { const pdfGenerator = () => { const doc = new jsPDF(); //I also attempted: new jsPDF('landscape', 'px', 'a4', 'false'); ...

What is the process for showcasing a local notification within my application?

Here is the code snippet I am working with: import { LocalNotifications } from '@ionic-native/local-notifications'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scs ...

Tips for utilizing angular ui.layout in column mode: Implementing a bottom-aligned element

Recently, I began utilizing angular ui-layout to enable pane splitting within a user interface. I am attempting to design a sidebar that features a blue element at the bottom. Is there a way to manipulate the ui-layout directive to accomplish this? I exp ...

Add a unique identifier to a table row in a jQuery/AJAX function without the need for a looping structure

My PHP query retrieves client data and generates a table with rows for each client. Each row contains a link with a unique ID attached to it. Clicking on this link triggers an AJAX function based on the client's ID, which opens a modal displaying info ...

Fixed position scrollable tabs with Material UI

I recently implemented material-ui scrollable tabs in my project, referencing the documentation at https://mui.com/material-ui/react-tabs/#scrollable-tabs. Here is a snippet of the code I used: <Tabs value={value} onChange={handleChange ...

Protecting Angular Routes: Verifying HTTP-Only Cookie Authentication on the Server- CanActivate Function

I am utilizing an HTTP only cookie for authentication in my server: export const checkCookie = async (req: Request, res: Response) => { const token = req.cookies["token"]; if (!token) { return res.status(401).json({ message: "Unau ...

Next.js' getInitialProps function does not fetch server-side data

I'm currently working through a tutorial on fetching data with Next.js Instead of following the tutorial exactly, I decided to use axios. However, I'm having trouble getting the desired data using getInitialProps. Here is my code: import axios ...

Is it necessary to have both Express and express-generator in my toolbox?

Recently delving into the world of node.js and stumbled upon express; While browsing the npm repository site https://www.npmjs.com/package/express, I noticed that the installation process is clearly stated as: $ npm install express However, further down ...

Using a function as an argument to handle the onClick event

I have a function that generates a React.ReactElement object. I need to provide this function with another function that will be triggered by an onClick event on a button. This is how I call the main function: this._createInjurySection1Drawer([{innerDra ...

Determine the text's length inside a div element by utilizing the div itself

I have a div with a fixed width of 30% and I am trying to find the length of the text within that div. Check out my JSFiddle for the code. The current code snippet I am using is: var text=$('#test').text(); text=text.trim(); var len=text.lengt ...

Guide on how to show the index value of an array on the console in Angular 2

Is there a way to show the array index value in the console window upon clicking the button inside the carousel component? The console seems to be displaying the index value twice and then redirecting back to the first array index value. Can we make it so ...

Updating JSON data using fetch API

Hi everyone, I'm currently working on an email application and need help with implementing an archive button for each email. It seems that the function to change the archived status to true is being called, but for some reason, it's not making th ...

Amazon Lex: Transforming Speech to Text with Audio Technology

Is there a JavaScript SDK provided by Amazon for converting audio files to text using Amazon Lex? I am currently working on a Node.js application and would like to achieve this functionality. ...

How to retrieve response cookies using RxJS Ajax

When using RxJS to make an Ajax call request, I am able to set the headers of the request. However, I am wondering how I can retrieve the Cookie from the RxJS Ajax Response? import { ajax } from 'rxjs/ajax'; ajax({ url: "some url", body: ...

Error: The property 'rows' cannot be read because it is undefined

While working through the steps outlined in Getting started with Postgres in your React app, specifically when processing and exporting the getMerchants, createMerchant, and deleteMerchant functions, I encountered an error that says: "TypeError: Cannot rea ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Navigating Date Conversion within Component in Angular 2 Application

Searching for a way to update the display of certain dates in my Angular 2 application, I encountered a roadblock. Using the date pipe in conjunction with string interpolation wasn't viable due to the structure of my template code: <input class="a ...

I am currently working with an input element that is set to hidden. I am trying to change its type to text using JavaScript, but I can't seem to figure out how to do it or if it is even possible

I'm stuck trying to change the type of an input element from hidden to text using JavaScript. I can't seem to figure out if it's even possible. Can someone please help me with this? Thanks! ...

Following conventional methods often results in oversized containers and monolithic code

I've heard that it's recommended to use classes for containers and functions for components. Containers handle state, while components are simple functions that receive and send props to and from the containers. The issue I'm encountering i ...