S3ck Stros
S3ck Stros

Reputation: 325

Remove validator after submitting

I created two textboxes one for the title and another for the name.

I am using validations if the textboxes are not filled, so the information is only submitted if both are filled.

My problem is that after submitting I try to clear the values ​​of the variables and when clearing that value the validation messages appear.

Is there a way to successfully submit and clear the value of variables, the validator does not appear?

DEMO

html

<div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="title..." [showClearButton]="true" [(ngModel)]="title">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Title">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>
<div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="name..." [showClearButton]="true" [(ngModel)]="name">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Name">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>

<dx-button text="Submit" [useSubmitBehavior]="true" (onClick)="Save()"></dx-button>

.ts

title: string;
name: string;

Save(){
  if(this.title == "" || this.title == undefined || this.name == "" || this.name == undefined){
  }
  else{
    alert("Sucess !!");
    this.title = "";
    this.name = "";
  }
}

Problem

Image

Here, I filled in the textboxes and submitted successfully. I cleared the value of the variables, but when doing this, the validator is activated, when in fact everything was supposed to be in the initial state :(

Upvotes: 3

Views: 1739

Answers (2)

Muhammed Moussa
Muhammed Moussa

Reputation: 5195

here a trick I'm usually using to clear all validators after submit.

  @ViewChildren(DxValidatorComponent) validatorViewChildren: QueryList<DxValidatorComponent>;

  private clearDxValidators = () => {
    this.validatorViewChildren.toArray().map(ref => {
      ref.instance.reset();
    })
  }


read more about reset()

Upvotes: 1

Dragos Andrei
Dragos Andrei

Reputation: 370

As a quick workaround, you can wrap the template in a form, then use that to check if it's pristine, in order to know whether or not to show the validator message. Then instead of assigning an empty string to your properties, you can reset the form (after importing it in the component through ViewChild()).

That does feel like a hack though, because the toolkit you're using should automatically know this. If it doesn't, then why bother use it.

Also, I suggest you also start reading on Angular Reactive Forms.

Anyways, I attached my suggested changes in a Stackblitz.

Good luck with your project!

Upvotes: 0

Related Questions