Why doesn't AngularJS validation function properly with input elements of type "number"?

Struggling with Angularjs validation here. Ng-pattern seems to work fine only when the input type is text. However, when the input type is number, ng-pattern doesn't seem to work, although required, min, and max attributes still function.

<input type="number" name="number" ng-model="myNumber" ng-pattern="reg" required />

https://jsfiddle.net/o4hr219m/

I attempted adding the attr[novalidate] for the form to prevent browser validation, but it didn't have any effect.

Does anyone have alternative solutions?

Your assistance would be much appreciated.

Thank you.

Answer №1

When setting the type="number", it is recommended to use $error.number instead of $error.pattern in Angular. This is because Angular will not bind the value to the model until it is deemed valid.

<span ng-show="myForm.number.$error.number">Invalid number</span>

For a visual demonstration, refer to the code snippet below:

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope) {

  $scope.reg = /^[0-9]*$/;

});
.error {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="homeCtrl">
    <form name="myForm">
      <label>Value Number</label>
      <input type="number" name="number" ng-pattern="reg" ng-model="value.number" /><span class="error" ng-show="myForm.number.$error.number">Invalid number</span>
      <br/>Current error for Value Number
      <pre>{{myForm.number.$error | json}}</pre> 

      <hr/>

      <label>Value Text</label>
      <input type="text" name="text" ng-pattern="reg" ng-model="value.text" /><span class="error" ng-show="myForm.text.$error.pattern">Invalid text</span>
      <br/>Current error for Value Text
      <pre>{{myForm.text.$error | json}}</pre> 
      <hr/>

      <input type="submit" value="Submit" ng-disable="myForm.$invalid" />
    </form>

  </div>
</div>

Answer №2

Check out the updated fiddle here: https://jsfiddle.net/o4hr219m/5/

JS

angular.module('pmsApp', []).controller('testCtrl',function($scope){
    $scope.reg= /^[0-9]\\d*$/;
})

HTML

<input ng-model="number" type="number" name="number" ng-pattern="reg"/>

In relation to your fiddle:

  • The module was not properly defined and ng-app was not utilized
  • Angular was loaded on load (should be placed in head or body instead)
  • No ng-model was added to the input, so validation will not function correctly
  • Avoid wrapping your regular expression with quotes

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

Incorporating React.js into HTML DOM Elements

As a beginner in react js, I'm facing an issue regarding DOM elements. Within my component, there is a table. When hovering over a cell, I want to highlight both the corresponding row and cell. Additionally, I need to obtain the coordinates of the hov ...

React-Image-Annotate encountered an issue: SyntaxError - The import statement cannot be used outside a module

Encountering an issue while trying to set up react-image-annotate. Here is the problem I am facing initially: https://i.stack.imgur.com/XgYPd.png This is how I have implemented it: import React from 'react' import ReactImageAnnotate from ' ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Issue with Lazy Loading in Angular 4 Universal

I recently created a new Angular CLI project to delve into server-side rendering with Angular Universal. Everything was set up and running smoothly, until I decided to implement lazy-loading for a module named 'lazy'. After implementing lazy-lo ...

The error stating that document.getElementById(...) is null has occurred within RSForms due to a TypeError

Issue: When clicking on the form to continue, a TypeError: document.getElementById(...) is null error occurs. Can anyone help me fix this problem? When I click on the continue button, it calls the function submitForm. <script type="text/javascript"> ...

What is the best way to create a more compact Select component in React?

Working on React's Select component has been quite the challenge for me. I'm in the process of creating a simple dropdown button, also known as a ComboBox, similar to what can be seen on GitHub Insights: https://i.stack.imgur.com/J9Bcd.png Belo ...

Ways to extract a specific line of text from HTML code

Can someone help me extract a specific line from an HTML code using Python? For instance, in this website: The snippet of code is as follows: var episodes = [[8,54514],[7,54485],[6,54456],[5,54430],[4,54400],[3,54367],[2,54327],[1,54271]]; I am lookin ...

Assigning a unique identifier to each table row when iterating through a collection using

I have successfully implemented code for generating a table dynamically with angularjs: <div class="col-lg-10 col-sm-10 col-xs-10"> <table class="table table-hover"> <thead> <tr> <th>item</th> <th> ...

Challenge with Alignment of Fields in Bootstrap's Horizontal Form

I am working on an Angular project with a horizontal form using Bootstrap. I have encountered a slight alignment issue with one of the date fields. The IsMessedUp datepicker input field is not aligned properly, positioned slightly to the left compared to t ...

Utilizing Selenium IDE and XPath to confirm that a checkbox is selected only when the associated label contains certain text

I need assistance in creating an Xpath query to validate if a specific checkbox is checked within the nested divs of the panel-body div. My goal is to ensure that a checkbox with the label "Evaluations" contains the class "checked". Below is the snippet of ...

Hide jquery scroll bar

I am currently working on a WordPress plugin with the Twenty Thirteen theme. My goal is to display a modal when a div is clicked, and at that time I want to hide the scrollbar on the body of the page. Despite trying the following code snippet, it doesn&ap ...

Button click causing TextField to print incorrectly

I am working on implementing a feature in my react application where users can input a search term, and upon pressing the button, it will be used to perform a search. The text input field and button are utilizing material-ui components. At this stage, I si ...

Reduce the noise from different versions by utilizing package-lock.json

There may not be a clear-cut answer, but I'm curious to hear how others handle the issue of package-lock.json causing problems when committing to their node repository. Many opinions lean towards committing package-lock.json - ensuring consistent dep ...

Eliminate jQuery's delayed blinking effect with the use of an event

Utilizing the mouseenter and mouseleave events, I have implemented a functionality to add a button (not actually a button) to an <li>. However, there seems to be a problem with my code. The button appears and disappears on mouseleave and mouseenter, ...

setTimeout executes twice, even if it is cleared beforehand

I have a collection of images stored in the img/ directory named 1-13.jpg. My goal is to iterate through these images using a loop. The #next_container element is designed to pause the loop if it has already started, change the src attribute to the next im ...

Load options from server directory using PHP jQuery AJAX

I am faced with a file structure on my server that resembles the following: My query is quite complex: How can I dynamically populate <select> HTML tags from the contents of sub-files on a server? For instance, I have 3 <select> tags here tha ...

Angular ngView not displaying content on the page

To load a ngView page by clicking on a link, the html file does not appear as expected. Running the application directly without using localhost might be causing the issue. I simply opened index.html with Chrome browser, so it's possible that there i ...

Add the item to a fresh array using the Ajax function

Here is an array that I have: var arrayOfResults = []; // Results after like statement After making a database call, I receive a JSON result like this: [{ "id": "{fcb42c9c-3617-4048-b2a0-2600775a4c34}", "pid": "{34214CCB-90C3-4D ...

Incorporate the value of a JQuery variable within an HTML form

When the Submit button is clicked, I am attempting to pass the value of currentDate to a REST GET service. However, there are two things that I don't understand. Is it possible to include the URL of the REST service in the action attribute of the fo ...

What is the best way to include overflow-hidden in the image displayed by the tailblock component?

I have implemented the following Tailblock component, which is built on tailwind.css. My goal is to achieve a hover effect where the image scales up within its original dimensions. I want the image to zoom in without changing its height and width. I atte ...