Retrieving ng-pattern as a variable from a service

Hey there! I'm currently working on an application that requires extensive form validation across multiple pages. To streamline this process, I am attempting to extract validation patterns from a service used among the controllers.

However, I've encountered an issue where the ng-pattern does not react correctly when inputting a valid email address.

You can view the plunker for reference and here's the code snippet for the form:

<form method="POST" action="#" name="newsletterForm" id="newsletterForm" ng-controller="newsletterForm" novalidate>
    <input ng-pattern="/{{patterns.email}}/" type="email" name="email" ng-model="email" required />
    <button type="submit">Submit</button>
    {{newsletterForm.email.$error.pattern}}
</form>

Below is the app.js code being referenced:

var app = angular.module('plunker', []);
app.controller('MainCtrl', function(){});
app.service('validationPatterns', function() {
    this.getPatterns = function() {
        return {
            email:  "^([a-zA-Z0-9\'\.\-\_]{2,64})([\@]{1})([a-zA-Z0-9\.\-\_]{2,64})([\.]{1})([a-zA-Z]{2,16})$"
        }
    }
});
app.controller('newsletterForm', function($scope, validationPatterns){
    $scope.patterns = validationPatterns.getPatterns();
});

I suspect that the issue may be related to how Angular renders the pattern within the input tag, possibly causing it to escape the backslashes.

^([a-zA-Z0-9'.-_]{2,64})([@]{1})([a-zA-Z0-9.-_]{2,64})([.]{1})([a-zA-Z]{2,16})$

I have attempted adding double backslashes in the service to ensure proper rendering by Angular, but unfortunately, it is still not functioning as expected. Any insights or suggestions would be greatly appreciated!

Answer №1

ng-pattern is designed to work with a $scope variable. In your situation, the correct implementation would be

<input ng-pattern="patterns.email" 

Check out the updated plunker example

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

Setting a dynamic ID attribute for a checkbox within a jQuery DataTable

I am working with a DataTables table that is populated with JSON data provided by a Java servlet. Each row in the table contains a checkbox. I have code that can add a check to every checkbox, but I need to find a way to evaluate the value of a specific fi ...

Implementing an interactive tab feature using jQuery UI

Recently, I was working on a project involving HTML and jQuery. Now, my goal is to create a dynamic tab with specific data when a button is clicked. This is my code for the JQuery-UI tab: $(document).ready(function() { var $tabs = $("#container-1 ...

Tips for detecting parallel processes using Node/JS programming language

Many software packages claim to execute their methods in parallel, such as the async npm package. They assert that even for functions like concat, they are processed concurrently. How can we verify if their assertion holds true? I have written code to te ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

Eliminate error class in jQuery Validate once validation is successful

I'm having an issue with the jQuery Validate plugin. Even after a field is successfully validated, the "error-message box" continues to be displayed. How can I remove this box? Here's my code: CSS: .register-box .field .has-error{ border ...

Direction of Scrolling

Is it possible to have a div move in the opposite direction of mouse scroll, from the top right corner to the bottom left corner? Currently, it is moving from the bottom left to the top right. #block { position: absolute; top: 400px; left: 100px; < ...

Transmitting an Array of Objects to a Web API using AngularJS

Throughout this process, I retrieve an array of "vehicles" from the Web API. I then make modifications and perform various actions on each vehicle. Afterwards, I aim to send back the updated list without the need for looping through it again. I have exper ...

React.js - "Encountered error: Unable to access 'map' property of undefined variable"

I've tried various methods I found through searching, but none of them seem to be working. Why is it still showing that map is undefined? import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/A ...

Remove the 'name' attribute from the input tag within the URL

Is there a way to make the server update the URL format to localhost:3000/userinput instead of localhost:3000/?name=userinput when submitting a name? Any suggestions would be greatly appreciated. Thank you in advance. ExpressJs FILE <!DOCTYPE html> ...

Legend click functionality works well in hiding the bars, but unfortunately, the data values in the charts.js are not being concealed as expected

When I click on the legend, the bar is hidden in the charts.js bar chart. However, the data value associated with the bar is not hidden. I have provided a link to the JS Fiddle code below: Check out the JS Fiddle here: https://jsfiddle.net/npyvw1L8/ var ...

Leveraging Angular js for performing operations in Putty

At the moment, we depend on Putty for connecting to the app server and checking logs. I am looking for a solution that would allow me to automate this process using angular js. Is it possible to send commands from my angular js or any other client-side a ...

Showing the updated list of items following deletion in AngularJS: A step-by-step guide

I am currently in the process of learning AngularJS and how to integrate it with ASP.NET Web API. My main challenge at the moment revolves around updating the list of products displayed on the page after a manager successfully deletes a product. The goal i ...

Utilizing express.js alongside the native MongoDB driver: A comprehensive guide

I'm facing difficulties when attempting a simple mongoDB query from my express app: app.js var express = require('express'); var routes = require('./routes'); var user = require('./routes/user'); var http = re ...

What causes the $injector:modulerr error when trying to integrate angular-carousel?

After integrating angular-carousel into my application, I encountered the following error: Failed to instantiate module ngMaterial due to: Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=n...) at Error (native) ...

If the width is below 767, the previous code will not be effective in jQuery

Challenge: How can I ensure that the code within the if statement only executes when the screen width exceeds 767px, and does not work if it is less than 767px? Using jQuery: $(document).ready(function() { $(window).resize(function() { if ($( ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

I am encountering an issue with CreateJS where I receive the error message: "createjs is not defined"

Looking for assistance with my createJS issue. var stage = new createjs.Stage(canvas); Encountering the following error : angular.js:13642 ReferenceError: createjs is not defined, even though I have EaselJS in my bower-components. Appreciate any hel ...

Changing state property upon clicking child element in React is not feasible

I am interested in changing the text color upon clicking it using a function triggered in a child element that affects the parent's state. This is because a specific property of the parent determines whether the text should be one color or another. W ...

how to use JSON to communicate between AngularJS controller and PHP

I am facing an issue with sending multiple data from JavaScript to PHP using AngularJS. Despite my efforts, I am unable to receive any data. As a beginner in AngularJS, I have included the following JS code: var data = {"name":name, "cin":cin, "job":job}; ...