Prevent special characters in input fields using Angular and TypeScript

I am currently working on an Angular project using Ant Design ng Zorro. I've encountered an issue with validation when trying to restrict special characters in an input field. Despite setting up the validation rules, it seems that the key press event is not triggering the validation. Does anyone have a solution for this?

html

<nz-form-item >
                <nz-form-control nzErrorTip="Company name is required!" >
                  <input
                    nz-input
                    placeholder="Type here"
                    formControlName="companyName"
                    nzSize="small"
                  />
                </nz-form-control>
              </nz-form-item>

.ts

 this.validateForm = this.fb.group(
 companyName: [null, [Validators.required, Validators.pattern('^[a-zA-Z \-\']')]],
)

Answer №1

It appears that the issue is due to missing {}. The fb.group() method expects an object.

The correct syntax should be:

this.validateForm = this.fb.group({
      companyName: [null, [Validators.pattern('^[a-zA-Z \-\']')]],
    }

For a working example, you can refer to this StackBlitz link

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

Ensure that missing types are included in a union type following a boolean evaluation

When working with typescript, the following code will be typed correctly: let v: number | null | undefined; if(v === null || v === undefined) return; // v is now recognized as a `number` const v2 = v + 2; However, if we decide to streamline this process ...

Encountered an unexpected import token in Angular2 (SystemJS)

i am trying to find a solution for this issue in my Angular2 project. I encountered an error and need assistance: `"(SystemJS) Unexpected token import SyntaxError: Unexpected token import at Object.eval (http://....../app.module.js:14:25) at eval (h ...

What is the best approach for retrieving a User from my Angular front-end service?

INQUIRY: I'm attempting to retrieve the details of the currently logged in user in my Angular 2 frontend service with the following code: UserModel.findById(userID, function (err, user) { It appears that this behavior is achievable from the browse ...

Expanding upon React Abstract Component using Typescript

Currently, I am in the process of building a library that contains presentations using React. To ensure consistency and structure, each presentation component needs to have specific attributes set. This led me to create a TypeScript file that can be extend ...

Initial request in the sequence is a conditional request

Currently, I am attempting to make a request in rxjs that is conditional based on whether or not the user has uploaded a file. If a file has been uploaded, I need to attach it to the user object before sending it off, and then proceed to patch the user aft ...

Tips for incorporating a child's cleaning tasks into the parent component

I am working with a parent and a child component in my project. The parent component functions as a page, while the child component needs to perform some cleanup tasks related to the database. My expectation is that when I close the parent page/component, ...

Preserve data even after refreshing the browser in Angular

Is there a reliable method to preserve my data after refreshing my browser? I've experimented with rxjs behavior subject, but it hasn't worked for me. I prefer not to use local/session storage due to security concerns and best practices, especia ...

Using an array of objects as a data source for the Material Angular table

My user data is causing some issues and looks like this... [{"firstName":"Pinkie","lastName":"Connelly","username":"Darlene.Marvin","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19506a767b7c75464b7c77777c6b5971766d74 ...

In Angular 2, property binding will not function properly when attempting to bind to an object

I have encountered a strange issue with Angular 2 property binding. Let's start with the Store class: export class Store { id: number; name: string; address: string; } This is the component code snippet: export class MyBuggyComponent i ...

The Angular HTTP post request fails to get sent

I have a simple post method defined as follows: createTask(taskName: String, parentTaskId: String) : Observable<any>{ let headers : HttpHeaders = new HttpHeaders(); headers.set('Content-Type', 'application/json; charset=utf-8&a ...

Is there a workaround for the React useContext issue in Typescript aside from using <Partial>?

I am currently working on a React app that utilizes the useContext hook, but I am facing challenges with correctly typing my context. Here is the code snippet in question: import React, { useState, createContext } from 'react'; import endpoints f ...

Arrange the "See More" button in the Mat Card to overlap the card underneath

I'm currently working on a project that involves displaying cards in the following layout: https://i.stack.imgur.com/VGbNr.png My goal is to have the ability to click 'See More' and display the cards like this: https://i.stack.imgur.com/j8b ...

What is the best way to eliminate Bootstrap from an Angular project?

When running my Angular project, I noticed that _reboot.scss is being uploaded and overwriting the styles of Angular Material. I attempted to remove it by following these steps: npm uninstall bootstrap Remove links from package.json Remove links from ang ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

What is the best way to transfer information to the canActivate service guard?

Here is the route definition: { path:'specific_path', component: specific_component, canActivate: specific_service} What is the best way to send data to the specific_service? ...

Error: The object is not defined (evaluating '_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView')

I am currently working on developing a chat application using react-native with the following dependencies: "dependencies": { "@react-native-async-storage/async-storage": "~1.17.3", "@react-native-community/masked ...

Error while conducting unit testing: Element 'X' is unrecognized

While running the command npm run test, I encountered a specific error in my terminal: 1. If 'app-general-screen' is an Angular component, then verify that it is a part of an @NgModule where this component is declared. 2. If 'app-general-sc ...

Error: Angular7 Unable to locate namespace 'google'

I am currently utilizing the import { MapsAPILoader } from '@agm/core'; package to enable auto-complete address search functionality. However, I have encountered an error message stating cannot find namespace 'google'. The error occu ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Troubleshooting path alias resolution issue in NextJS when using Typescript with index.ts files

I keep receiving a TypeScript warning stating that the module cannot be found. This issue has surfaced while I'm utilizing TypeScript in my NextJS application, particularly when using custom paths. Previously, this problem never arose. My project st ...