1

Consider a form whit this Validation that updates on submit like this:

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've putted the if condition to check if the form is not valid and just return. To achieve that if the form is invalid the input is not allowed to change value, but it's not working. Even when I typed something that is not allowed for the input and hit the submit button the form becomes invalid but values also gets updated.

screenshot

Tried also with onUpdate blur.

Michael Rovinsky
  • 6,807
  • 7
  • 15
  • 30
sam1928
  • 13
  • 5

2 Answers2

0

I think you want to prevent user to enter invalid characters.

In that case, pattern is not enough because as you have it, angular is doing the validation, which is fine.

I recommend to use a directive as explained here in the second solution: https://stackoverflow.com/a/41479077/1133816

In your case, you should use your regex.

georgeos
  • 2,351
  • 2
  • 24
  • 28
  • Not exactly, i need something like e combination of updateOn submit & change. Validation should be done on changing the input field and update it on submit. Need to mention that the form is in a modal. – sam1928 May 31 '21 at 06:03
0

A Validator not avoid you write an invalid value, only indicate is invalid

You can subscribe to valueChanges and use pairwise rxjs operator

  this.myForm.get('name').valueChanges.pipe(
    startWith(this.myForm.value.name),
    pairwise()
  )
  .subscribe(([oldValue, newValue]) => {
    if (this.myForm.get('name').invalid) 
        this.myForm.get('name').setValue(oldValue,{emitEvent:false});
  })
Eliseo
  • 50,109
  • 4
  • 29
  • 67