What is the best way to validate ng-pattern as the user begins typing in AngularJS (input field length > 0)?

Is there a way to validate the input field length and check for a specific pattern if it is greater than zero?

Expectation:

  1. If the input field is empty, display a required message (when touched).
  2. As the user starts typing, validate the pattern. If the pattern does not match, show a "Please Enter Valid Input" message. If the input field length is 0, only show the required message.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-messages.js"></script>


<div ng-app='ngMessagesExample'>
   <form name="test" novalidate ng-submit="test.$valid && submit()">
      <div layout-gt-md="row">
         <md-input-container class="md-block" flex-gt-xs>
            <label>Number</label>
            <input  required ng-model="user.number" name="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" >
            <div ng-messages="test.number.$error">
            </div>
            <div ng-messages="test.$error" ng-show="test.number.$dirty">
               <div ng-message="required">number is required</div>
            </div>
            <span ng-show="!test.number.$valid">Please Enter Valid Input</span>
         </md-input-container>
      </div>
   </form>
</div>

View demo here

Any assistance would be greatly appreciated!

Answer №1

I have made updates to the HTML code

<!doctype html>
<html lang="en">
<head>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular-messages.js"></script>
  <script src="script.js"></script>

</head>
<body>

  <div ng-app='ngMessagesExample'>
    <!-- Application content will go here -->
     <form name="test" novalidate ng-submit="test.$valid && submit()">
    <div layout-gt-md="row">
   <md-input-container class="md-block" flex-gt-xs>
      <label>Number</label>
      <input  required ng-model="user.number" name="number" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" >
      <div ng-messages="test.number.$error">


      </div>
      <div ng-messages="test.$error" ng-show="test.number.$dirty"><div ng-message="required">Number is required</div></div>

      <span ng-show="test.number.$error.pattern">Please Enter Valid Input</span>
   </md-input-container>
</div>
</form>

</div>
</body>
</html>

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

The conditional validation feature of the jQuery Validation Engine allows for dynamic validation based on

In my Angular SPA, I have a form that incorporates Jquery validation engine for validation purposes. The form consists of a check box and a text-box. I want the text-box to be required only if the check box is checked, and this functionality is working as ...

Issue with AngularJS function not being executed when ng-submit button is clicked

I am facing an issue with a bootstrap modal that contains a form. The submit button is not triggering a function defined inside my AngularJS controller. Despite being able to read and display data on the page, clicking the submit button does nothing except ...

The event binding for input with the specific class `.SomeClass` in the document is functional in Chrome, but encounters issues in Internet Explorer

I am facing an issue where I have a span with the contenteditable attribute and a function to detect input within it. //TextArea <span class="SomeClass" contenteditable></span> //Function $(document).on("input", ".SomeClass", function () { ...

Tips for updating a value within ng-repeat only if the value is equal to "string"; otherwise, hide it from display

I'm having trouble updating the data in my table to display "Yup" or blank space based on certain conditions. I am new to this and tried a solution, but it's not working: {{ person.value ? "Yup":" "}} .. Can anyone help me with this? angular.m ...

Is there a way to access the pixel data of a scene in Three.js without having to render it on the canvas?

Is there a way to obtain the pixel data (in the form of an array buffer) that would be displayed on a canvas if I were to render a scene, without actually rendering it on the canvas? If so, how can this be achieved? I have not written any code for this ye ...

Error message: "wp is not defined" appears when using TinyMCE, Bootstrap Modal, and URL Parameter together

Currently utilizing Bootstrap 5 alongside WordPress 6.2 In the process of developing a WordPress plugin, where I have successfully created a Dashboard and an All Content page. On the Dashboard page, users can find a list of the most recently created cont ...

Utilizing ES6 JavaScript for Creating Static Methods and Angular 2 Services

During the development of an Angular 2 app involving multiple calculation services, I encountered some interesting questions: Is it beneficial to use static in an Angular service provided on the application level? Or is it unnecessary? How does a static ...

Use the JavaScript .replaceAll() method to replace the character """ with the characters """

My goal is to pass a JSON string from Javascript to a C# .exe as a command line argument using node.js child-process. The JSON I am working with looks like this: string jsonString = '{"name":"Tim"}' The challenge lies in preserving the double q ...

Creating interactive PDF files using ReactJS

Is there a way to create a PDF using React that supports styling and allows the content to be hidden on the page? I need to have a link in my app that, when clicked, generates a PDF and opens it in a new tab. I've tried out various packages but none s ...

Developing a JSON structure that is able to be deserialized within a C# environment

While attempting to generate a JSON object that can be interpreted as a C# object, I continually encounter 400 bad request errors when sending it via AJAX. Here's my JavaScript snippet: $.ajax({ type: "POST", url: "LeagueService.svc/Fixtures ...

The Magic of Javascript Routing with Regex Implementation

I'm currently developing a Javascript Router similar to Backbone, Sammy, and Spin. However, my specific requirements are rather straightforward. I need the ability to define a series of routes along with their corresponding callbacks, and I want to be ...

Restrict the number of GET requests made using D3.js and the Twitter API

Currently, I have made adjustments to my D3.js chart by switching from mouseover/mouseout events to mousemove. While this change has caused several issues in the chart, the most significant one pertains to my GET statuses/show/:id requests. In the past, h ...

What's the Reason Behind My Array Populating on Rebuild but Not on Page Refresh?

I am currently utilizing a tech stack that includes Vue 3 with Composition API, a Pinia store, TypeScript, a SQL backend, and Fetch to retrieve data through my .NET 6 API. Within my codebase, I have a User.ts class: export default class User { userNam ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...

Tips on accessing a file in v-file-input

<v-file-input accept="image/*" label="File input" v-model="chosenFile" ></v-file-input> I'm working with Vue.js. How can I access the content of the files? var reader = new FileReader(); var img = ...

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...

In JavaScript, the gallery feature with Lightbox effect creates a unique touch as only half of the screen fades to black in

Hello everyone, I'm a complete beginner when it comes to programming so please be gentle with me on my first question :) I'm trying to put together a simple website with a lightbox gallery, and you can check out what I have so far here. The prob ...

What is the rationale behind Typescript permitting the assignment of an "any" object type to a class object?

Within my codebase, there is a class object that I have initialized: groupNameData: GroupNameData = new GroupNameData(); In addition, I also have an any object called groupNameDatas. groupNameDatas: any; Experiment 1 (class = any) To experiment with ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Modify the values in a textbox using JavaScript to suit your needs

unusual issue: I'm encountering a strange bug with my form. I have an ajax datepicker attached to a text box, but when I submit the form, all values are received except for those from the datepicker checkboxes. Why is the .Text property empty for th ...