What could be causing the issue with the [pattern] not functioning properly in Angular 5?

In my .ts component file, I have a variable that aims to prevent invalid phone numbers from being entered:

public phonePattern = ^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$;

In the HTML component file, there is a text box defined as follows:

<input type="text" [(ngModel)]="contact.phone" [pattern]="phonePattern" placeholder="Enter Phone Number" />

The binding for [pattern] does not appear to be functioning correctly. Any suggestions on how to fix this?

Answer №1

Consider using the following approach to initialize your regex:

emailRegex = /^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,3})+$/;

Make sure to validate that your regex pattern is accurate before proceeding.

Answer №2

Utilize Model-driven forms as they come equipped with built-in methods for validating regular expressions.

import { FormGroup, FormControl, Validators } from '@angular/forms';
.
.
.
class ModelFormComponent implements OnInit {
  myform: FormGroup;

  ngOnInit() {
    myform = new FormGroup({
        name: new FormGroup({
            firstName: new FormControl('', Validators.required), 
            lastName: new FormControl('', Validators.required),
        }),
        email: new FormControl('', [ 
            Validators.required,
            Validators.pattern("[^ @]*@[^ @]*") 
        ]),
        password: new FormControl('', [
            Validators.minLength(8), 
            Validators.required
        ]),
        language: new FormControl() 
    });
  }
}

Check out this example of a model-driven form here

   

Answer №3

What I ultimately decided to do was create a method in the component like this:

number;
matchesRegex; //Custom method definition

  ngOnInit() {
    //Define custom method
    this.matchesRegex = function () {
      if (this.number === null) {
        return false;
      }
      return this.number.match(/^-?[1-9]?\d[,]-?[1-9]?\d$/gm);
    }
  }

Then, in my HTML template:

<input [(ngModel)]="number" [ngClass] = "{'is-valid': matchesRegex()}">

This approach works well because it is checked every cycle and updates as the user types. This can be used to prevent submission or disable a button based on certain conditions. In my case, I applied it to add a CSS class. The built-in validator prevents submitting an invalid pattern.

Answer №4

Develop a custom directive for validating phone numbers.

import { Directive } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[phone]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: PhoneValidatorDirective, multi: true }
  ]
})
export class PhoneValidatorDirective implements Validator {
  constructor() {}

  validate(control: AbstractControl): { [key: string]: any } {
    if (control.value && !/^-?[1-9]?\d[,]-?[1-9]?\d$/gm.test(control.value)) {
      return {
        phone: 'Invalid phone number'
      };
    }

    return null;
  }
}

You can now include the phone attribute in your input field for validation.

<input type="text" [(ngModel)]="contact.phone" phone placeholder="Enter Phone Number" />

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 formatting in vscode does not apply to .tsx files

For a while now, I've relied on the Prettier extension in Visual Studio Code for formatting my code. However, since switching to writing React with Typescript, I now need to configure Prettier to format .tsx files accordingly. ...

The issue with VueEditor in Nuxt.js is that it's throwing an error

When working on my Nuxt.js project, I integrated the vue2-editor package for writing articles with HTML. Everything functions properly when I enter text and submit it, however, upon reloading the page, I encounter an error stating "document is not defined" ...

What is the best way to iterate through two object keys in TypeScript?

I recently created a Vector class but I am encountering some issues with the syntax. Here is the code snippet: export class Vector { x: number; y: number; constructor(x = 0, y = 0) { this.x = x; this.y = y; } add(v: Vector) { var x ...

When troubleshooting the "Uncaught reference error: require is not defined," the browserify command encountered the error message "Error: Cannot find module."

I am encountering a similar issue to @RachelD in the thread discussing the Uncaught reference error. When I execute the 'browserify' command following the instructions provided here, and using my directory as a reference, like so... myname@compn ...

What is the process for transforming a Typescript source file into JavaScript?

I have a basic HTML file with a script source set to index.ts. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge ...

Having trouble getting my asynchronous promise to work properly

I am currently working on implementing a login server function and I am struggling to understand why the promise I'm making is not being called. My setup involves using MongoDB with Mongoose as the backend, which is connected to using User.findOne. A ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Exploring the intricacies of Knockout JS mapping nested models using fromJS function

I am struggling with understanding how to effectively utilize the Knockout JS Mapping Plugin. My scenario involves nested models, and currently I am only using the ko.mapping.fromJS() in the parent model. However, I have noticed that the computed values ar ...

Tips for generating rows with material-ui grid

I am utilizing material-ui grid to make my content responsive. However, I am facing challenges in creating nested rows for my layout. My requirement is to have the first row span the entire width and then divide it into 3 columns with widths of 3, 3, and 6 ...

Avoiding the use of an animated feature in JQuery

I've created a function that adds a little intro animation, but now I want to add a skip button so users can jump straight to the main page if they don't want to watch the intro. However, my attempts to implement this feature seem to be failing. ...

Challenges encountered when attempting to align faces within Three.JS stemming from the use of two distinct

I'm currently facing an issue with my three.js code. My goal is to align two objects by selecting two faces and rotating the second face (and object) to match the normal vector of the first object's selected face. Here is what I have so far: v ...

tips for resizing bootstrap dropdown menu to fill entire page

The image clearly shows that the zabubi solution network platform has a dropdown menu with the label "no request for collaboration to be accepted" on top. The menu occupies half of the page and does not seem to be responsive. Even when the page is resized, ...

Challenges with the insertedCount in Express and MongoDB

I am facing an issue with using "insertedCount" in MongoDB in a NodeJS project. Upon calling the "insertOne()" method, the const assigned does not allow me to access the insertedCount value as it returns "undefined". Below is my app.js code: const { MongoC ...

Managing HTTP Requests on a Website Using HTTPS

On my html page, I have references to Java script files hosted by Google using Http. However, since my site is Https, the page loads with a message saying "Only secured content is displayed." I need to change these calls to use Https instead of http. I at ...

Executing a Jquery click event after a delay with setTimeout

I am working with an <a> element that, when clicked, triggers a handler like this: function onCummReportClick(e) { if ($(e.currentTarget).attr('href').indexOf('csv') !== -1) { { return true; } //Here s ...

Do specific elements of typography adjust according to the size of the window?

I'm always amazed by the creative solutions that come out of this community. So I'm reaching out to see if anyone knows a way to achieve something unique with CSS! Specifically, I'm curious if it's possible to make certain horizontal p ...

What is the most effective method for determining if an object contains a particular property?

Can anyone advise on the best approach to check if an ajax response object has a specific property? I've done some research and it seems there are various methods to do this. One way is: if(ajaxResponse.hasOwnProperty('someProperty')){ ...

Is there a way to position one DIV behind another?

Hey, I'm working on my first project and running into some trouble with divs. I'm trying to position the firework behind the central text but can't figure it out. Can anyone lend a hand? I need to add more details in order to submit the que ...

A guide to optimizing JavaScript through Django templates and RequireJS

Scenario: Using Django with Django-Compressor for CSS Implementing nested templates using Django templatetags Incorporating RequireJS to import JS modules. Illustration: base.html: <html> ... <script src="/static/js/libs/require.js"> ... { ...

Unable to showcase Google Maps in VS 2015 with Angular 2 integration

Here is a snippet of code for a component I created: import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles: [`.sebm-google-map-container { height: 300px;}`], template: `<sebm-google-map [latitude]="la ...