【问题标题】:form validation not working while submitting form提交表单时表单验证不起作用
【发布时间】:2019-12-05 19:57:12
【问题描述】:

我创建了一个表单并且功能正常工作,但我在验证方面遇到了一些问题。

验证不起作用,如果表单中有任何错误,我想限制表单提交,并且还想对电子邮件(如果是电子邮件字段)、文本输入和数字输入应用验证。

你可以在这里查看我的代码:https://stackblitz.com/edit/angular-ay58g9

【问题讨论】:

  • 你想禁用提交按钮还是什么?
  • 不禁用但不应该提交表单并且应该显示错误消息。此外,电子邮件验证不工作
  • 感谢您的快速帮助,但提交按钮始终处于禁用状态
  • 那么@eliseo 的回答会有所帮助!

标签: angular angular-forms


【解决方案1】:

请试试这个。我用的是有棱角的材料,所以也请看一下

<form name="f" (ngSubmit)="f.form.valid && submitForm(f)" #f="ngForm" novalidate>
  <mat-form-field class="w-100">
    <mat-label>First Name</mat-label>
    <input type="text" matInput name="firstName" [(ngModel)]="data.firstName" #firstName="ngModel" required>
    <mat-error *ngIf="firstName.invalid">
      <span *ngIf="firstName.errors.required">Firstname Is Required</span>
    </mat-error>
  </mat-form-field>

  <mat-form-field class="w-100">
    <mat-label>Email</mat-label>
    <input type="text" matInput name="email" [(ngModel)]="data.email" #email="ngModel" required
      pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" required (keyup)="findDuplicateUserEmail(f)">
    <mat-error *ngIf="email.invalid">
      <span *ngIf="email.errors && email.errors.required">Email Is Required</span>
      <span *ngIf="email.errors && email.errors.pattern"> Email Is Incorrect</span>
    </mat-error>
  </mat-form-field>

  <button type="submit" mat-raised-button color="primary">Create</button>
</form>

【讨论】:

    【解决方案2】:

    我喜欢

    <!--pass the form-->
    <form [formGroup]="form" (ngSubmit)="submit(form)">
    

    在.ts中

    submit(form:FormGroup)
    {
       if (form.valid)
       {
                 ..here you get something with the form.value..
       }
       else
          form.markAllAsTouched() //<--to show errors
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多