Having difficulty validating the field accurately with Angular.js

In order to validate the input field in accordance with the user's needs using AngularJS, I have shared my code below:

<div ng-class="{ 'myError': billdata.longitude.$touched && billdata.longitude.$invalid }">
  <input type="text" name="longitude" id="longitude" class="form-control oditek-form" placeholder="Add Longitude coordinate" ng-model="longitude" ng-pattern="/^[0-9]+([,.][0-9]+)?$/" ng-keypress="clearField('businessno');">
</div>
<div class="help-block" ng-messages="billdata.longitude.$error" ng-if="billdata.longitude.$touched">
  <p ng-message="pattern" style="color:#F00;">This field only allows numbers (e.g. 0,1..9).</p>
</div>

The requirement here is that users should be able to enter numbers only with a + or -, such as +123.45 or -095.4567. However, currently, the use of + or - is not allowed, only numbers are permitted.

Answer №1

Make sure to enable the appropriate symbols in the regular expression pattern.

ng-pattern="/^(\+|-)?[0-9]+([,.][0-9]+)?$/"

Answer №2

ng-pattern="/^([+|-][[0-9]+([,.][0-9]{n,m}))]?$/";

It is recommended to use the provided pattern and replace 'n' with the minimum number of decimal places allowed, in this case being 0, and 'm' with the highest number of decimal places permitted.

Answer №3

Creating your own directive for custom validation is a great way to enhance your AngularJS application. Here's an example:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.2.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="app" ng-controller="HomeCtrl">
    <div>
      <form novalidate name="myForm">
        Number: <input type="text" name="valText" ng-model="val" even-number />
      </form>
    </div>
    <div>
      <span style="color: red;" ng-show="myForm.valText.$error.evenNumber">Invalid value</span>
      <br />
      <br />
      <button ng-click="setValue(22)">Change Value to 22</button>
      <br />
      <button ng-click="setValue(19)">Change Value to 19</button>
    </div>
  </body>

</html>

Check out the live demo on Plunkr!.

With this Even Number directive, only even numbers are allowed for validation.

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

Troubleshooting AngularJS POST Request Error with Request Body

I am a beginner in AngularJs and I am trying to make a post request to a server with enum form. Currently, I have the following JavaScript code: function completeTaskAction2($scope, $http, Base64) { $http.defaults.headers.common['Authorization'] ...

Ways to retrieve an individual item using Puppeteer

Can Puppeteer retrieve a single element instead of an array? Often, we see code like this: const elements = await page.$$('.some-class'); Is there a way to get just one element without returning an array? ...

What level of trust can be placed in MUI Global Class names when using JSS?

Here is my current code snippet: const formControlStyles = { root: { '&:hover .MuiFormLabel-root': { } } } Would it be considered secure to utilize the class name in theme overrides for connecting with other components? Furthe ...

What does the error message "unsupported command-line flag" in Chrome mean for Protractor?

Recently jumping on the Protractor bandwagon, I found myself facing an issue while running my tests on Chrome (an error message appears below the address bar in the browser): A worrisome warning popped up saying something about '--ignore-certificat ...

Utilize Content Delivery Network Components in Conjunction with a Command Line Interface Build

As we progress in building our Vue applications, we have been using the standard script tag include method for Vue. However, as we transition from jQuery/Knockout-heavy apps to more complex ones, the maintenance issues that may arise if we don't switc ...

What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs this.listNumber = [ { "GenericQuestions": [ { "input": "long", }, { "input": & ...

What is the most effective method for fetching images from MongoDB?

I'm currently working on a web application that uses MongoDB's GridFS to store and retrieve images. However, I'm facing an issue where retrieving images from the database takes significantly longer than expected when a user makes a request. ...

Fixing the Jquery Clone Bug

Recently, I came across a jQuery clone plugin that is designed to fix the values of cloned textarea and select elements. This code snippet showcases how it works: (function (original) { jQuery.fn.clone = function () { var result = ori ...

various functions being managed in version 1.0.5 versus 1.2.19

As I work on updating an application from angular 1.0.5 to 1.2.19, I've come across a puzzling issue. To better illustrate the old behavior, you can view this fiddle. Take note of the console output and compare it to the new angular version showcased ...

Error: Unable to find the specified "location.ejs" view in the views directory

I am encountering the following error - Error: Failed to find view "location.ejs" in views folder "e:\NodeJs_Project\geolocationProject\views" at Function.render Your help in resolving this issue would be greatly appreciated. server.js ...

Dealing with a passed EJS variable in string form

When working with passed data in ejs, I usually handle it like this and it works perfectly: let parsed_json = JSON.parse('<%-JSON.stringify(passed_data)%>'); However, I encountered a problem when trying to dynamically pass a string variabl ...

Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original. Check out my code below: window.onload = function() { ImageObjSketch = new Image(); // URL ImageObjSketch.src = 'https://i.imgur.com/75lATF9 ...

What is the best way to eliminate excess space on the right side in Bootstrap 4 while in mobile view?

I'm struggling to understand why this layout is not responsive on mobile devices, triggering a bottom scroll bar at around 616px. I'm looking for a solution to hide the scroll bar at least until 414px for iPhones and other smartphones. I've ...

Tips for creating CSS styles for a selected input field

I seem to be stuck in a situation where my screen looks similar to the screenshot provided. There are four input elements that I would like to have bordered just like in the image, complete with a circled tick mark. I've managed to create these four i ...

Continuing to use a function multiple times may lead to a type error as it is not a

My program is designed to be a quiz where users have to answer questions. After answering, they will see a summary and then get the option to submit or redo the questions. The issue arises when users choose to redo a question. Upon redoing it, the summary ...

Dynamic Data Causes Highcharts Date Formatting to Adapt

I wanted to create a line graph using Highcharts with the Date Format on x-axis set to "%b %e". For example, I expected 06/27/2014 to be displayed as Jun 17. Despite setting the date-format correctly, Highcharts seems to automatically change it when rende ...

Flag form field as invalid in AngularJS

Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message? Here's the setup of my app: I have a model 'client' with a controller Accounts.controller(&ap ...

RequestDispatcher.forward() does not work when servlet is invoked through an Ajax POST request

My login page involves user authentication through the firebase and sending the request to a servlet. When I click the submit button with correct credentials, the firebase authentication works, the servlet is called but an error is displayed in the browser ...

The proper translation of the HTML encoded string is not being rendered accurately within AngularJS

I am dealing with an HTML encoded string that looks like this: Sign up and get &lt;span class=&quot;strong&quot;&gt;Something for FREE!&lt;/span&gt; When I implement ngSanitize and ng-bind-html in my template as shown below: ...

Require checkboxes in AngularJS forms

Currently, I have a form that requires users to provide answers by selecting checkboxes. There are multiple checkboxes available, and AngularJS is being utilized for validation purposes. One essential validation rule is to ensure that all required fields a ...