Having trouble with Angular 6 Validators.pattern() RegEx Function?

I've been attempting to implement a regular expression with the Validators.pattern() for Angular 6 FormBuilder, but for some reason, the validation is not working as expected. I even tested the RegEx on https://codepen.io/devtips/pen/gzqKKP and it was accepted there.

The pattern I came up with is

/^[(0-9)]*[\s][\d]{1,5}-?[\d]{1,5}$/
, and I'm trying to validate formats like (000) 000-0000 and (000) 0000-0000. However, despite this, the input field always shows an invalid result.

buildAgentDetailsForm() {
this.agentDetailForm = this.fb.group({
  FirstName: ['', [Validators.required, Validators.nullValidator]],
  LastName: ['', [Validators.required, Validators.nullValidator]],
  Email: ['', [Validators.required, Validators.email]],
  Phone: [
    '',
    [
      Validators.required,
      Validators.pattern(/^[(0-9)]*[\s][\d]{1,5}-?[\d]{1,5}$/)
    ]
  ],
  EmergencyPhone: ['', [Validators.required]],
  Address: ['', [Validators.required]]
  });
}

Could my expression be incorrectly written? It's worth mentioning that I have implemented a mask on the input field to restrict input and include characters like () and the dash.

Answer №1

To enhance your validation, consider using the following pattern:

Validators.pattern("[(0-9)]*[\\s][\\d]{1,5}-?[\\d]{1,5}")

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

Personalized validation using Bootstrap V5

Currently, I am using the default Bootstrap V5 form validator and I am interested in finding a way to create a custom parameter that must be checked for the input to be considered valid. Specifically, I want users to input their license plate, which should ...

Group Matching Regardless of Sequence

# Example Data Frame df <- data.frame(Column_A =c("1011 Red Cat", "Mouse 2011 is in the House 3001", "Yellow on Blue Dog walked around Park")) I have a column of manually entered data that needs some cleaning. ...

How can I prevent the modal from appearing each time I navigate back to the page where it is displayed from another page?

Currently, I am in the process of developing a web application using Node.js with Express, Mongoose, and EJS. One of the key features of my app is a modal that appears after a user logs in or signs up, then redirects to the dashboard page. This modal displ ...

Uploading images with Laravel and VueJS

I am having trouble with Vuejs image upload. My backend is Laravel, but for some reason the images are not being sent to the Controller. <form method="POST" class="form-horizontal" role="form" v-on:submit.prevent="updateProduct(editProduct.id)" en ...

Discovering the attribute of a DOM element (or, to be more precise, the class of a div)

Here's the code snippet I'm working on: <body class="asdf"> <span>hey! <div class='hideContent'>test</div> the ultimate experience</span> <span id="blarg">original</span> </b ...

What are the steps to generate an image upon clicking a button?

Here's what I have now: <script> function display() { var element = document.getElementById('display'); element.innerHTML='<img src=\"display.png\">'; } </script> And the HTML code: <input type ...

React JS - State values are not persisting and rendering properly upon clicking

Recently, I followed a step-by-step tutorial on creating a todo list using functional components. However, I encountered an issue when attempting to delete or mark items as complete in the list. In both the deleteHandler and completeHandler functions, I tr ...

Enhancing local storage arrays with Javascript

I am attempting to utilize JSON.parse and JSON.stringify to store and update an array in local storage. However, the process doesn't seem to be functioning as expected. let existingArray = JSON.parse(localStorage.getItem("yesArray")); existin ...

Achieving Full Screen Height in Angular Component

Trying to nest an angular component within another one that occupies the entire screen using height:100%; in the component's css file. I want to stack them and ensure each component takes up the full screen height, but setting height:100% doesn't ...

Utilizing Struts2, jQuery, and `document.getElementById` to retrieve undefined values from form fields in JavaScript

When I submit this form, I am encountering undefined values in the browser console. Have I made a mistake in the code somewhere? Oddly enough, I receive correct values when submitting other forms within the same project. Here is the exact error image: $( ...

Guide to sending back a promise using JQuery

Here is the Durendal code I am working with: var variable = ko.observable(""); function activate(){ return myModel.doSomething(variable); } The doSomething function looks like this: function doSomething(variable){ if(someCondition) return ...

Retrieve the TaskID of an ECS Fargate container for exporting and future use within AWS CDK code

Currently, I am leveraging CDK version 2 alongside Typescript. In my current setup, I encounter a situation where I necessitate the TaskID value from ECS Fargate Container to be incorporated into another command. The process involves me utilizing new ecs ...

I am having trouble with the Array Reverse function, it's not functioning properly

Take a look at this React JS code snippet: poll() { var self = this; var url = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40'; $.get(url, fu ...

Troubleshooting problems with dynamic elements and qTip

On my page, I have an UpdatePanel where new forms are added when clicked. These new elements contain images that need to utilize qTip. This is the current setup: $(document).ready(function () { $('.ttip').qtip({ conten ...

Despite having both React and Firebase enabled, the "sign-in provider" feature appears to be disabled

Within my Authentication settings, the Sign-in Method is configured to use Email and Password as enabled. I've set up a handler for form submission that looks like this: createUser(e){ e.preventDefault(); const email = this.createEmail.value ...

When attempting to invoke the rest function, an error occurs stating that the dataService.init in Angular is not

Learning AngularJS has been my current focus. To practice, I have been working on a Quiz app tutorial. However, I encountered an issue when trying to call the rest function of a factory after injecting it into one of my controllers. The JSON data for this ...

Changing the language can lead to an ExpressionChangedAfterItHasBeenCheckedError when the translated value is found within a mat-option

Choose a value from the dropdown menu, then toggle the switch button. An error message labeled 'ExpressionChangedAfterItHasBeenCheckedError' will appear in the console. Click here for an example This issue cropped up after upgrading my Angular ...

Issues with preg_replace function

I am encountering an issue with a string that includes the title "The Incredible Hulk (2008)" and I am attempting to use a specific pattern to remove the "(2008)". The PHP code I have implemented is as follows: $x = trim(preg_replace("/^\([0-9]{1,4}& ...

Quickly deliver a text file to the user - API Controller C#

After spending several hours searching and struggling to prompt a download of a text file from the server to the User's machine, I've decided to seek help here. The function is located in an ApiController. public class LogViewerController : ApiC ...

Update the mat-chip-remove positioning attributes

While browsing through the mat-chip documentation, I came across the following information: MatChipRemove Provides proper (click) support and styling for using the Material Design "cancel" icon, which can be found at https://material.io/icons/#ic_cancel. ...