如何对angular中的必填字段进行表单验证

时间:2014-06-19 04:03:17

标签: angularjs

我想通过使用Angular表单验证来验证我的表单。我已阅读了许多文章,这些文章提供了有关如何在提交之前验证表单的信息。但我的问题是我如何验证所需字段的表单 例如对于我的登录表单,我有两个字段一个用户名和密码。无需输入任何字段值,用户单击登录按钮。所以在这个场景中如何进行角度验证。

提前致谢,

2 个答案:

答案 0 :(得分:1)

以下是验证表单的代码(根据我的要求在验证程序中使用的电子邮件构建)

Login.Component.html

<form id="loginForm" #validform="ngForm" (ngSubmit)="onSubmit(validform)">
    <div class="example-container">

        <mat-form-field>
            <input matInput placeholder="UserName" [formControl]="userName" autofocus>
            <mat-error *ngIf="userName.hasError('email') && !userName.hasError('required')">
                Please enter a valid email address
            </mat-error>
            <mat-error *ngIf="userName.hasError('required')">
                Email is
                <strong>required</strong>
            </mat-error>
            <br>
        </mat-form-field>
        <mat-form-field>
            <input matInput type="password" placeholder="Password" [formControl]="password">
            <mat-error *ngIf="password.hasError('required')">
                Password is
                <strong>required</strong>
            </mat-error>
        </mat-form-field>


    </div>
    <button type="submit" class="btn btn-success btn-block" [disabled]="userName.hasError('email') || password.hasError('required')"
        id="login_btn">Login</button>
</form>

Login.Component.ts

import { Component,OnInit, OnChanges, Injectable } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators,NgForm, NgModel } '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'
  ]
})


export class LoginComponent implements OnInit {

/* validate form */
validform;

userName : any;
password : any;

constructor(){ }

ngOnInit(){
         this.buildForm();
}
buildForm(){
   this.userName = new FormControl("", Validators.compose([
        Validators.required,
        Validators.email,
      ])),
      this.password =   new FormControl('', [
        Validators.required,
      ])}
onSubmit = function(validform: NgForm){
       //Call the login api with validForm Data
}


 }

希望这会有所帮助。

答案 1 :(得分:0)

只需在提交按钮上添加ng-disabled即可。这样的东西应该可以工作。你必须给表单一个角度验证的名称来处理它。

<form name="myform">
  <input type="email" name="email" ng-model="email" placeholder="Email Address" required /></input>
  <input type="password" name="password" required></input>
  <button type="submit" ng-disabled="myform.$invalid"> Submit </button>
</form>