防止在Angular 5中验证后提交表单

fro*_*.io 2 forms typescript angular angular5

我有以下代码出于演示目的,显示了一个简单的带有错误消息和提交按钮的表格行:

<form [ngFormOptions]="{updateOn: 'submit'}">
   <tid-form-row>
      <label tid-ui-label for="temperatureInput">Temperature:</label>
      <input [tid-ui-input]="{required: true}" id="temperatureInput" name="temperatureName" placeholder="20,4"
             [(ngModel)]="temperatureModel" #temperature="ngModel" [tidDigits]="{integer: 2, fraction: 1}" required>
      <ng-template #hint>
         <small tid-ui-hint>The yellow color indicates that this field is required.</small>
      </ng-template>
      <div tid-ui-error *ngIf="temperature.invalid && (temperature.dirty || temperature.touched); else hint">
         <span *ngIf="temperature?.errors.required">Field is required.</span>
         <span *ngIf="temperature?.errors.tidDigits">Must be max 2 integer digits and max 1 fraction digit.</span>
      </div>
   </tid-form-row>
   <tid-button type="submit">Check validation</tid-button>
</form>
Run Code Online (Sandbox Code Playgroud)

这里tidDigits是一个自定义的ValidatorDirective与此ValidatorFactory

export function digitsValidator(config: any): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const value = control.value;
    const errorObject: any = {tidDigits: {value: control.value}};
    let passed = true;

    if (value) {
      const [integer, fraction] = value.split(',');
      if (config.integer && config.integer >= 0) {
        if (integer.length > config.integer) {
          passed = false;
          errorObject.tidDigits.integer = integer.length;
        }
      }
      if (config && config.fraction && config.fraction >= 0) {
        if (fraction.length > config.fraction) {
          passed = false;
          errorObject.tidDigits.fraction = fraction.length;
        }
      }
    }
    return passed ? null : errorObject;
  };
}
Run Code Online (Sandbox Code Playgroud)

我希望演示在用户单击提交按钮时显示不同的错误消息。因为这是演示表单,所以我根本不希望提交表单。

当该字段为空(required-Validator)或例如输入tidDigits20,44 (-Validator)时,错误消息会正确显示(按下提交按钮之后)。但是,如果输入有效值(例如20,4),则表单提交-即重新加载页面并将字段名称附加到URL:/tid-form-row?temperatureName=20,4

有什么办法可以阻止表单提交?

我尝试了(ngSubmit)="onSubmit()"onSubmit() { return false; }并且也(ngSubmit)="$event.preventDefault()"按照此处的说明进行了操作,但是没有用。还有其他想法吗?

Adr*_*lat 5

<button>标记中type属性的默认值为submit,如果要防止这种情况,则需要用以下方法覆盖:

<button type="button"></button>
Run Code Online (Sandbox Code Playgroud)

删除是type="submit"不够的,更多详细信息在这里:HTML按钮不提交表单


如果仍然要进行验证,则可以尝试以下操作:

<form #form>
    <button type="button" (click)="validateForm(form)"></button>
</form>
Run Code Online (Sandbox Code Playgroud)

并且,在您的Typescript代码中:

public validateForm(form: NgForm) {
  for (const control in form.controls) {
    control.updateValueAndValidity();
  }
}
Run Code Online (Sandbox Code Playgroud)