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

Integration of AngularJS with PHP for Seamless User Authentication

As a newcomer to angularjs, I find the Login Process a bit confusing. Every time I log in, I'm automatically redirected to a specific page that is already set in the code. I just want a simple check to see if the user is logged in. If they are, then ...

Enter a socket.IO chat room upon accessing an Express route

Encountering difficulty when attempting to connect to a socket.IO room while accessing a specific route in my Express application. The current setup is as follows: app.js var express = require('express'); var app = express(); var http = requir ...

Tips for passing props while clicking on a v-data-table:

I am currently facing an issue in my app while using v-data-table. I am able to pass props with an extra slot, but I want the entire row to be clickable in order to open a dialog with the prop item: <template v-slot:item.actions="{ item }"> ...

What is the best way to incorporate JQuery into html content retrieved through an ajax request?

In my jsp file, there is a div structured like this : <div id="response" class="response"></div> After triggering an ajax call to a servlet, the content of this div gets updated with the following elements : <div id="response" class="res ...

Protractor: Decrease the magnification

Currently, I am working with protractor and facing the challenge of zooming out to 50%. Despite trying numerous solutions found on StackOverflow, none have successfully resolved the issue. Some attempted solutions include: browser.actions().keyDown(protra ...

Chrome Developer Tools - Array Length Discrepancies

While exploring Chrome DevTools, I came across an inconsistency that caught my attention. The screenshot above shows the issue I encountered. Initially, it indicated that the object contained a Body and a Head, with the head being an array of length 1. Ho ...

Struggling to render images within a child component in a React application when passed as a prop from the parent component

Currently immersed in a React project, here is the structured layout of my work: public index.html src App.js images facebook.png image.PNG linkedin.png profile.png twitter.png Profile Intro profileIntro.js data data.js Within App.js, I import ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

Connect my Vue.js model data to the object that will be used for submission

I need help figuring out how to bind data from my input field into my Vue.js model. I've tried putting the UnitName inside the model but it's not working. Can someone provide some guidance on how to achieve this? new Vue({ el: "#app", da ...

The Jquery script is ineffective for newly added elements

After creating an Ajax Form that functions well, I noticed that when the result of the form is another form, my script does not work for the new form generated. Is there a way to make the new form function like the old one? $(document).ready(function() ...

Integrating a bokeh chart within a Flask application

Upon accessing localhost:5002/simpleline via Flask, I was hoping for a straightforward bokeh plot. Instead, what I encountered was unexpected: ('', ' ') I have two essential files involved in this process. Firstly, the Python file: f ...

The preflight OPTIONS request for an AJAX GET from S3 using CORS fails with a 403 error

I have come across various discussions and issues related to this topic, but unfortunately, I have not been able to find a solution yet. I am attempting to use AJAX GET to retrieve a file from S3. My bucket is configured for CORS: <?xml version="1.0" e ...

Locate the class ID and refine the search results by another class

I am currently working on a task that involves extracting the first <li> element's id where it has the class name my_class, and checking if the <span> with the class Time contains a ":" using jquery. Below is the sample HTML structure: & ...

Update the configurable product process for the custom attribute 'delivery_time' in Magento 1.9.2

I am currently using Magento 1.9.2.4 (1.9.2.3 in my Testpage) and I have a few configurable products with multiple options. Each product (child of the configurable one) has a different delivery time. To achieve this, I created an attribute called "delivery ...

Struggling to modify a document in a MongoDB collection with an HTTP Put request?

I've recently started working with AngularJS and I encountered an issue while trying to update my MongoDB Database. I'm facing a problem when attempting to update an object within my collection. The code snippet below showcases my approach: //li ...

Performing Jasmine unit testing on a component that relies on data from a service, which itself retrieves data from another service within an Angular 2+ application

Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases. saveservice.service.ts -- file const ...

Issue encountered: NPM error, unable to find solution for resolving dependency and addressing conflicting peer dependency

I am facing difficulties deploying my project on netlify due to NPM errors. Below are the dependencies: "dependencies": { "@angular/animations": "~15.1.1", ... (list of dependencies continues) ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

Tips on replacing views within ion-view and updating the title in the title bar to match the injected page through the use of Ionic and AngularJS

I am new to ionic and angular JS. I am currently working on a simple app within the ionic framework. My goal is to inject an HTML template into the ion-view tag using ngRoute. However, I am facing issues as my code is not successfully injecting the HTML te ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...