Angular: Despite form validation indicating invalid, the input still gets updated

Imagine a scenario where a form with validation updates upon submission as shown below:

Html

<div class="form-row">
   <form [formGroup]="myForm" class="col-3" (submit)="onSubmit()">
     <label for="name">Name</label>
     <input class="form-control" formControlName="name" id="name" name="name" />
     <button class="button" type="submit">Save</button>
   </form>
    
Value: {{ myForm.value.name }}
<br />
Is form valid {{ myForm.valid }}
</div>

And in the ts file:

ngOnInit(): void {
   this.myForm = this.fb.group(
            {
              name: ['', [Validators.required, Validators.pattern(/^[^\d].*/)]],
            },
            { updateOn: 'submit' }
   );
}
    
onSubmit() {
   if (this.myForm.invalid) {
     return;
   } else {
     console.log('Form is Valid');
   }
}

I have included an if condition to check if the form is invalid and simply return. The objective was to prevent the input from changing values when the form is deemed invalid. However, this approach does not seem to be effective. Even when entering inappropriate data into the input field and submitting the form, the form is marked as invalid but the values still get updated.

I also attempted using onUpdate on blur without success.

Answer №1

A Validator will not prevent you from entering an invalid value; it will only indicate that the value is invalid

To track changes in a form field, you can subscribe to valueChanges and use the pairwise rxjs operator

  this.myForm.get('email').valueChanges.pipe(
    startWith(this.myForm.value.email),
    pairwise()
  )
  .subscribe(([prevValue, nextValue]) => {
    if (this.myForm.get('email').invalid) 
        this.myForm.get('email').setValue(prevValue,{emitEvent:false});
  })

Answer №2

To prevent users from entering invalid characters, simply using a pattern may not be sufficient. Angular handles validation in this case, but I suggest implementing a directive for more control. You can find detailed instructions in the second solution provided here: https://example.com/directive-solution

Make sure to incorporate your regex into the directive for customized validation.

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 issue arose when attempting to save a nested list of schema types in Typegoose and Mongoose, resulting in a failed Cast to

Encountering this issue: Error: Competition validation failed: results.0: Cast to ObjectId failed for value "{ name: 'David'}" The main model is as follows: class Competition { @prop() compName: string @prop({ ref: () => C ...

What is the best way to conditionally render one of several components in a manner that is compatible with React's change detector?

Within my CRUD application, I have incorporated various reusable components such as a "generic" DialogComponent, along with several non-reusable components. Throughout the development process, I have encountered numerous instances where I need to either: ...

Having trouble updating npm using npm install npm@latest -g and encountering an error?

Encountering errors and warnings while updating npm to the latest version c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External>npm cache clean --force npm WARN u ...

Implementing Apollo GraphQL code generation for NextJS frontend development

Currently, I am facing an issue while trying to type out my front end react queries with Apollo in nextJS. Despite multiple configurations attempts, I keep getting an unknown error on my query when using import {gql} from src/__generated__/gql. Hovering ov ...

Preserving quotation marks when utilizing JSON parsing

Whenever I try to search for an answer to this question, I am unable to find any relevant results. So please excuse me if this has been asked before in a different way. I want to preserve all quotation marks in my JSON when converting from a string. In m ...

Surprising end tag found in Angular2

I am currently delving into Angular2 with TypeScript and have hit a roadblock after making some initial changes. Here is the issue I am facing. My code snippet is as follows: import { Component } from '@angular/core'; @Component({ select ...

What is the method for using Angular to bind to the page size in a print style sheet?

Is there a way to bind to a print style sheet and programmatically set the page size in Angular? For example: @page { size: {{ width +'mm' }} {{ height + 'mm' }} } If so, how can this be achieved? ...

Having trouble generating a bin executable for my npm package

Referencing: https://docs.npmjs.com/cli/v10/configuring-npm/package-json#bin I am attempting to generate a "binary" for my npm package. The structure of my package.json is as follows: { "name": "@internal/my-exe", "version": "0.0.0", "type": "commo ...

What is the best way to pass input values to directives?

Is there a way to dynamically pass input field values to directives and then send them to a server via post request? I am looking for a solution on how to achieve this functionality. This is my HTML code: <input type="text" [appHighlight]="appHighligh ...

Setting up a route configuration to automatically redirect users to a parent and child route upon app launch

After searching through the Udemy tutorial and Angular2 documentation, I still can't figure out why my redirect isn't working. I want my app to directly navigate to the /whatsup/today component upon loading, but despite successfully redirecting t ...

What is the best way to place a dragged item on top of a dropped item?

I'm attempting to transfer data between two kendo grids using HTML5 drag and drop events. However, when I use ev.target.appendChild(document.getElementById(data));, I receive an error stating that data is not a node type. My goal is for the dropped da ...

Preserving type information while dynamically adding functions to an object

Within my functions.ts file, I have defined 2 functions. Each of these functions accepts an api object and returns a function with varying argument types, numbers, and return types. export function f1 (api: Api) { return function (a: number): number[] { ...

The CORS policy is blocking Angular Socket.io Node.js because the requested resource does not have the 'Access-Control-Allow-Origin' header present

When trying to access the socket endpoint from my frontend, I encounter this error message: chat:1 Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=NOAlAsz' from origin 'http://localhost:4200& ...

Updating Mat-Form-Field styles in Angular 15

I am looking to customize the appearance of a Mat-Form-Field with the outline style. The goal is to have a white background and a white border for this field. https://i.sstatic.net/EyZK3.png Our attempts so far include: encapsulation: ViewEncapsulation. ...

Web API encountering 502 Error due to excess amount of data

Tools Utilized The application I am working on incorporates angular 2 and web API technologies. Specifically, I am making use of $http calls in Angular to interact with the web API service method. Current Task at Hand The API method is primarily responsi ...

Displaying Mat-error from response in Angular and Django user authentication process is not functioning as expected

Currently, I am working on the Signup page and facing an issue with handling 'if username already Exists'. I have successfully logged the Error message I want to display in the Console but it is not appearing on the Mat-error Label. This snippet ...

What are the steps to fixing the TS2722 error that says you cannot call a possibly 'undefined' object?

Here is a snippet of code from my project: let bcFunc; if(props.onChange){ bcFunc = someLibrary.addListener(element, 'change',()=>{ props.onChange(element); //This is where I encounter an error }) } The structure of the props ...

Please provide me with the steps to relocate the src/pages/api folder to src/ in a Next.js project

When working with Next.js, I am interested in relocating the src/pages/api directory to be located under src/, much like how it is done in blitz.js. In this case, the directory structure would look something like this: src |- pages |- api Unfortunately, I ...

What is the best way to elucidate this concept within the realm of TypeScript?

While diving into my ts learning journey, I came across this interesting code snippet: export const Field:<T> (x:T) => T; I'm having trouble wrapping my head around it. It resembles the function definition below: type myFunction<T> = ...

Which is better to test: JavaScript or TypeScript?

As I delve into TypeScript, I find myself in a conundrum. In my JavaScript days, I relied on Jest for testing. Now that I'm working with TypeScript, I've come across ts-jest. But here's the thing - do I actually need it? After all, my TS cod ...