Prevent user from submitting form if form is still the same

88 views Asked by At

So I want to prevent a user from submitting a form if the form is untouched/still the same. The form has a submit button which calls my submitChanges() function when clicked. This is what my function looks like in the TS.

submitChanges() {
// Do nothing if the form is still the same
if (!this.myForm.dirty || this.myForm.invalid) {
   return;
}

else
//...submit the form...
}

Problem: The logic seems to be working until I type something in the form and backspace whatever I typed. It thinks the form is still dirty even though I backspaced everything I typed, so the question is how can the form know it's not dirty anymore since the input has been removed (backspaced)?

2

There are 2 answers

2
Derrick Rose On

You could make a method and on focusout of the input that does this:

if(this.form.controls.formControl.value === '') {
   this.formControl.markAsPristine();
   this.formControl.markAsUntouched();
}

It will prevent you from being able to submit the form. I'd also recommend using the [disabled] attribute to prevent the user from being able to click on the button if the form is not valid.

0
Eliseo On

the only you make a custom form validator

  isEqual(value:string)
  {
    return (control)=>{
      return control.value==value?{error:'must be different to '+value}:
                            null
    }
  }

You use like, e.g.

  control=new FormControl('one',this.isEqual('one'))

see this stackblitz