【问题标题】:Prevent Submitting Form after Validation in Angular 5在Angular 5中验证后防止提交表单
【发布时间】:2018-01-03 16:02:43
【问题描述】:

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

<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>

其中tidDigitscustom 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;
  };
}

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

当字段为空 (required-Validator) 或例如输入 20,44 (tidDigits-Validator)。但是,如果输入了有效值(例如 20,4),则表单提交 - 即重新加载页面并将字段名称附加到 URL:/tid-form-row?temperatureName=20,4

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

我尝试了(ngSubmit)="onSubmit()"onSubmit() { return false; } 以及(ngSubmit)="$event.preventDefault()",如here 所述,但没有成功。还有其他想法吗?

【问题讨论】:

    标签: angular forms typescript angular5


    【解决方案1】:

    &lt;button&gt; 标签中 type 属性的默认值是submit,如果你想防止这种情况,你需要覆盖它:

    <button type="button"></button>
    

    删除 type="submit" 是不够的,这里有更多详细信息:HTML button to NOT submit form


    如果您仍然想验证,也许您可​​以尝试以下方法:

    <form #form>
        <button type="button" (click)="validateForm(form)"></button>
    </form>
    

    并且,在您的 Typescript 代码中:

    public validateForm(form: NgForm) {
      for (const control in form.controls) {
        control.updateValueAndValidity();
      }
    }
    

    【讨论】:

    • 当我更改类型时,它确实没有提交 - 但它也不会再验证输入了。
    • 试试你加(click)="yourValidateFunction()"?
    • &lt;form #form ... &lt;button (click)="form.controls['temperatureName'].updateValueAndValidity()" ...(来自here)试过,但它仍然没有验证。控制台日志:Cannot read property 'temperatureName' of undefined 还有其他想法吗?
    • "Cannot read property 'foreach' of undefined"... 我想我会切换到反应形式 :) 还是谢谢!
    • @PimHazebroek 不知道。我更新了答案以考虑您的观察。
    【解决方案2】:

    尝试删除按钮上的type="submit"

    如果您在form 元素上定义了(ngOnSubmit),则任何submit 按钮都会激活该功能。我通常只在表单内的按钮上使用(click) 事件监听器来激活功能。

    您是否有理由绕过输入更改的验证?不幸的是,您正在收听submit。因此,您可能需要稍微回溯并重新设计解决方案。当按钮具有(click) 事件时,您可以在表单控件上运行updateValueAndValidity。不过,要使其中大部分工作,您可能需要使用响应式表单而不是模板驱动表单。

    查看AbstractControl

    【讨论】:

    • "submit" 是表单中的默认按钮类型,不是吗?客户要求不是在模糊或更改时而是在提交时验证输入字段。这里的问题是,我需要 Angular 的“提交”操作来验证表单——但我想阻止表单被提交,即使验证成功也是如此。切换到响应式表单是可能的,但需要付出一些努力。
    • 如果我是你,我会切换到反应形式。并设置您的(ngOnSubmit) 函数以在表单控件上运行updateValueAndValidity() 函数。我想你可能会用模板驱动的方法碰到天花板。
    猜你喜欢
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多