简体   繁体   中英

Calling validate function before submiting the form using ngNativeValidate

Hi I am trying to call the validate(ngNativeValidate) function on click of button.

My form look like:

<form #myForm="ngForm" (ngSubmit)="addEndpoint(myForm.value);" ngNativeValidate>
        <section class="form-block">
            <div class="form-group">
                <input type="text" placeholder="name" name="name" [(ngModel)]="myData.name" [hidden]="true">
            </div>
            </section>
        <button type="button" class="btn btn-outline" (click)="testEndpoint(myForm.value);">TEST CONNECTION</button>
        <button type="submit" class="btn btn-primary" [disabled]="disableSubmit">SUBMIT</button>
    </form>

Validation works as expected for SUBMIT button. I want the same behavior even for TEST CONNECTION button. but don't want to submit the form. How I can do it? I think there will be some way to just call the validator function on-click event. Any help is appreciated. Thanks! in advance.

EDIT: testEndpoint is a backend call function.

In reactive forms you can use the 'valid' and 'touched' properties of the form to display feedback to the user if what you are trying to do with 'Test connection' button is to check user inputs.

Therefore, you could skip the 'test connection' button and directly output the following span if the form is invalid and the button submit disabled:

<button type="submit" class="btn btn-primary" [disabled]="disableSubmit">SUBMIT</button>
<span *ngIf="!myForm.valid && myForm.touched" class="help-block">Please enter valid data!</span>

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM