Issue with ng-pattern directive not working as expected within AngularJS

<label for="updateInterval" class="control-label"  for="UpdateInterval">Choose Interval</label>    
<input name="intervalRange" id="intervalRange" ng-pattern="" type="number" class="form-control input-medium fld-updateinterval-val" placeholder=""  ng-model="update_interval" ng-required="true" >

<select class="form-control input-medium sampleForm-combo" onchange="changetextbox(this.value)" id="action" ng-model="update_intervalSelect" ng-required="true">
    <option></option>
    <option value="days">days</option>
    <option value="hours">hours</option>
</select>

In the above code snippet, there is an input field and a dropdown menu. The value entered in the input field depends on the selection made in the dropdown menu. While the JavaScript functions correctly, there seems to be an issue with the ng-pattern attribute not functioning as expected. Despite the ng-pattern being set in Firebug, inputting numbers outside of the specified range is still allowed.

function changetextbox(interval)
{
if(interval == "days"){
    $(".fld-updateinterval-val").attr("placeholder", "1-365");
    $(".fld-updateinterval-val").attr("ng-pattern", "/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/");
}

else if (interval == "hours"){
    $(".fld-updateinterval-val").attr("placeholder", "1-8760");
    $(".fld-updateinterval-val").attr("ng-pattern", "/\\b([1-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8760)\\b/");
}

Answer №1

Simply adding the ng-pattern attribute to an input tag or making changes as described above will not suffice. The element needs to be compiled using the $compile service for it to function correctly.

Another straightforward method to achieve the same result is to bind it with a scope variable.

angular.module('textInputExample', [])
  .controller('ExampleController', ['$scope',
    function($scope) {
      $scope.example = {
        text: 'guest',
        word: /[a-z]/,
        changengpattern: function() {
          this.word = /[0-9]/;
        }
      };
    }
  ]);

HTML

<form name="myForm" ng-controller="ExampleController">
    Single word:
    <input type="text" name="input" ng-model="example.text" ng-pattern="example.word" required ng-trim="false">
    <span class="error" ng-show="myForm.input.$error.required">
    Required!</span>
    <span class="error" ng-show="myForm.input.$error.pattern">
    Single word only!</span>

    <tt>text = {{example.text}}</tt>
    <br/>
    <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt>
    <br/>
    <tt>myForm.input.$error = {{myForm.input.$error}}</tt>
    <br/>
    <tt>myForm.$valid = {{myForm.$valid}}</tt>
    <br/>
    <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt>
    <br/>
    <input type="button" value="click me to change ng pattern" ng-click="example.changengpattern()" />
  </form>

Here is a functional fiddle for you

Answer №2

After encountering similar difficulties, I discovered that angular requires both a starting and ending tag within your regex pattern. To address this, adjust your examples as follows:

$(".fld-updateinterval-val").attr("ng-pattern", "/^\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b$/");
$(".fld-updateinterval-val").attr("ng-pattern", "/^\\b([1-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8760)\\b$/");

It is crucial to note that the pattern string should commence with /^ and conclude with $/. By adhering to this format, my issues with custom ng-patterns were successfully resolved.

Answer №3

ng-pattern= "/^([0-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]\d|8760)$/"

Answer №4

Enter the regular expression

("/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/")
within the ng-pattern input.

For instance,

ng-pattern="/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/"

This method proved successful for me....

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

Can SVN hooks be incorporated into NPM in a way that is comparable to git hooks?

I want to incorporate an npm script that performs linting and testing before executing an svn commit. If there are any failures during the linting or tests, I want the commit process to halt, similar to a git commit hook. Does anyone have any recommendat ...

PhantomJS version 2.1.1 encountered an error on a Windows 7 system, displaying "ReferenceError: Map variable not found."

I've been utilizing the "MVC ASP.NET Core with Angular" template. I'm attempting to incorporate phantomJS and execute the tests, but encountering the following errors: ERROR in [at-loader] ..\\node_modules\zone.js\dist&bs ...

Tips for boosting the tabindex in a React search result list with ul-li elements

Implementing search results using ul li: <ul className="search-result"> <li tabindex="1">title here...</li> <li tabindex="2">title here...</li> <li tabindex="3">title here... ...

Error: The class constructor [] must be called with the 'new' keyword when creating instances in a Vite project

I encountered an issue in my small Vue 3 project set up with Vite where I received the error message Class constructor XX cannot be invoked without 'new'. After researching online, it seems that this problem typically arises when a transpiled cla ...

Effective strategies for organizing component features in React

As I was reading through the React documentation, I came across the idea that using React effectively involves following the Single Responsibility Principle, meaning each component should have a specific purpose. I've already created a basic Gameboard ...

What steps should I follow to include a message in the custom form validation rule in my React application?

I'm currently developing a chat application using React 18 and Firebase 9. For cleaner form validation, I have integrated the Simple Body Validator. Within the Register form, there's an input field of type file for uploading user avatars. The ...

Setting the current date as the default in an input box using ng-it: a step-by-step guide

How do I automatically set today's date as the default in the input box using ng-it? Here is my Plunker I am simply looking to set today's date as the default in the input field using ng-it. Would appreciate it if you could check out my P ...

Ajax modal login feature refuses to close

Struggling to close a modal login box? Everything seems to be functioning correctly with the modal screen and ajax features, but I'm facing issues when it comes to closing the modal form. The code snippet looks like this: HTML: <a href="#" cla ...

The exact measurement of width is not specified in the custom element that extends HTMLCanvasElement

I have created a custom element that extends a canvas, but when I try to add it to the DOM, the width appears to be undefined. Here is my code snippet. class Renderer extends HTMLCanvasElement { constructor() { super(); } } customElements.def ...

Updating AngularJS: Removing the hashtag using history.pushState()

Struggling to enhance the aesthetics of the URLs in my AngularJS application, I am facing some challenges. While I can access the "/" route without any issues, the "/about" route seems to be out of reach. Please note that the project is situated at (loc ...

Retrieve the HTML structure from an AJAX response

I'm working on an Ajax call in my code: callAjaxController: function(){ var url = Routing.generate('ajax_price'); $.ajax({ type: "GET", url: url, cache: false, success: funct ...

How can I show the unique phrase "Today" on a specific date (date=today) with the Angular-UI-Bootstrap Datepicker?

I'm currently integrating the Angular-UI datepicker directive into my project and I'm facing an issue. I want to have the datepicker display 'Today' instead of the actual date like 2015/04/27. Is there a way to achieve this without hav ...

Unable to resolve eslint rule for formatting case statements within a switch statement

Looking at my sublime text window, I have a screenshot showing the eslint error that is being thrown for the switch / case statement. I'm aiming to indent 4 spaces, as shown in the code. https://i.sstatic.net/oQi63.png Here are 4 different attempts ...

Showcasing the values of JavaScript

How can I resolve the issue depicted in the second picture? I need the value of 3 only in the USD column, with all others having a value of zero. <div class="span3"> <ul class="nav nav-tabs nav-stacked" > <?php foreach ( ...

The Best Way to Align a Large Image in the Middle of a Browser Window Using Inline HTML

Currently, I am attempting to center an image that is 1920px wide within the browser window. The challenge lies in not having it fit entirely within the window, so using width:100% will not achieve the desired effect. Furthermore, this needs to be accomp ...

Utilizing Vue's v-for directive to display computed properties once they have been fully loaded

Utilizing the v-for directive to loop through a computed property, which is dependent on a data attribute initialized as null. I'm planning to load it during the beforeMount lifecycle hook. Here's a simplified version of the code: <th v-for= ...

Numerous Firebase queries triggering the "10 $digest() iterations reached" error

As an example, I aim to create a list structured like this: Apple - Steve Jobs Microsoft - Bill Gates Tesla - Elon Musk To achieve this, I will utilize two Firebase applications in conjunction with AngularJS. The first Firebase app is organized as follo ...

Angular is patiently waiting for the initial function to activate

I have a situation where I need to wait for the results of my first function before executing the second one. code First function getUser() { this.authService.user().subscribe( user => { this.user = user; console.log('c ...

"Step-by-Step Guide: Implementing a Modal Popup Form in Angular with NgBootstrap and FormsModule

I am seeking assistance with my Angular project. I am attempting to implement a Modal Popup Form using NgBootstrap and FormsModule, but encountering issues with the NgbModule not being imported. Here are some details of my setup: node 16.15.1 cli 15.1.5 co ...

What is the best way to implement JavaScript code that can modify the layout of a website across all its pages?

I am facing an issue on my website where, on the index page, clicking a button changes the background color to black. However, this change is not reflected on other pages even though I have linked the JavaScript file to all HTML documents. How can I make i ...