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.