简体   繁体   English

angular2中的Form Builder验证

[英]Form Builder validation in angular2

my problem is when the user click the submit button without filling the mandatory field it must show error.I searched a lot i didnt find the solution am new to angular so anyone help me to solve the problem. 我的问题是,当用户在没有填写必填字段的情况下单击提交按钮时,它必须显示error.I搜索了很多内容,但我发现该解决方案不是角度问题的新手,因此有人可以帮助我解决问题。

 <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="wpcf7-form"> <p></p> <div formGroupName="serviceProviderDetail"> <input formControlName="mobileStatus" placeholder="Please enter your name" type="hidden"> <div formGroupName="user"> <h6>First Name</h6> <p><span class="wpcf7-form-control-wrap your-name"> <input formControlName="firstName" placeholder="Please enter your name" type="text" name="firstName" id="firstName" [formControl]="firstName" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" > <div*ngIf="myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].dirty && myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].invalid "class="alert alert-danger"> Please enter a firstName </div> </span> </p> </div> <button type="submit" class="btn btn-warning" style="background-color:#FF812D;font-size:18px;width:200px;text-align: center;margin-left: 37%;margin-bottom: 5%;">Submit</button> </div> </form> 

Use required in input tag for more detailed validations formvalidator 在input标签中使用必填项,以进行更详细的验证formvalidator

 <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="wpcf7-form"> <p></p> <div formGroupName="serviceProviderDetail"> <input formControlName="mobileStatus" placeholder="Please enter your name" type="hidden"> <div formGroupName="user"> <h6>First Name</h6> <p><span class="wpcf7-form-control-wrap your-name"> <input required formControlName="firstName" placeholder="Please enter your name" type="text" name="firstName" id="firstName" [formControl]="firstName" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" > <div*ngIf="myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].dirty && myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].invalid "class="alert alert-danger"> Please enter a firstName </div> </span> </p> </div> <button type="submit" [disabled]="myForm.valid" class="btn btn-warning" style="background-color:#FF812D;font-size:18px;width:200px;text-align: center;margin-left: 37%;margin-bottom: 5%;">Submit</button> </div> </form> 

在输入字段中使用required =“ true”

<input formControlName="firstName" placeholder="Please enter your name" type="text"   name="firstName" id="firstName" [formControl]="firstName" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" required="true" >

There were syntax issues and no code provided for the reactive form so I pared down the example to firstName and its error message. 存在语法问题,没有为反应形式提供任何代码,因此我将示例缩减为firstName及其错误消息。 Guessing by the formControlName syntax, I assumed you're using reactive forms but let me know if you were trying to use template forms instead (eg ngModel). 通过formControlName语法进行猜测,我假设您使用的是反应形式,但如果您尝试使用模板形式(例如ngModel),请告诉我。

  1. Flag the control as required: Construct the firstName form control with Validators.required : firstName: ['', Validators.required] 根据需要标记控件:使用Validators.required构造firstName表单控件: firstName: ['', Validators.required]
  2. Disable submit while the form is invalid: Submit button should be disabled when the form is invalid , not when it's valid: <button [disabled]="myForm.invalid">Submit</button> 在表单无效的情况下禁用提交:在表单无效而不是有效的情况下,应禁用<button [disabled]="myForm.invalid">Submit</button><button [disabled]="myForm.invalid">Submit</button>

I noted your question asked to show the message when the user clicked the submit button with an empty string . 我注意到当用户单击带有空字符串的“提交”按钮时,要求您显示该消息的问题。 Instead, this approach disables the button when the form is invalid, as it will be when the user has not given a first name. 而是,此方法在表单无效时禁用按钮,就像在用户未提供名字时一样。 If the user starts to give a first name and removes it, the error message will display reminding the user that the field is required (looks like you already had that working) and the button will disable again. 如果用户开始提供名字并将其删除,则将显示错误消息,提醒用户该字段是必填字段(看起来您已经可以使用该字段了),并且该按钮将再次禁用。

form.component.html: form.component.html:

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
  <div formGroupName="serviceProviderDetail">
    <h6>First Name</h6>
    <input formControlName="firstName" placeholder="Please enter your name" type="text" name="firstName" id="firstName">
    <div *ngIf="firstNameControl && firstNameControl.dirty && firstNameControl.invalid" class="alert alert-danger">
      First name is required
    </div>
    <button type="submit" [disabled]="myForm.invalid">Submit</button>
  </div>
</form>

form.component.ts form.component.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  myForm: FormGroup;

  get firstNameControl() {
    return this.myForm.controls['serviceProviderDetail'].controls['firstName'];
  }

  constructor(_fb: FormBuilder) {
    this.myForm = _fb.group({
      serviceProviderDetail: _fb.group({
        firstName: ['', Validators.required]
      })
    });
  }

  onSubmit(value) {
    console.log('Submit value:', value);
  }

}

Hope this helps. 希望这可以帮助。 Here's a plunker to keep tinkering, let me know if this missed what you were asking. 这是一个不断努力的小伙子 ,让我知道这是否错过了您的要求。

I have followed the same form control for my ionic project. 对于我的离子项目,我遵循相同的表单控件。 PFB the registration page. PFB注册页面。 Ignore the ionic tags and everything else is same and you can get idea for your Angular 2 project too. 忽略离子标签,其他所有操作都是相同的,您也可以从Angular 2项目中获得灵感。 Declare the form and control variables in below typescript file 在下面的打字稿文件中声明形式和控制变量

public signUpForm:FormGroup;
    public name:FormControl;
    public email:FormControl;
    public userId:FormControl;
    public faculty:FormControl;
    public terms:FormControl;

PFB the HTML file PFB HTML文件

<form [formGroup]="signUpForm" (submit)="register()">
            <ion-card>
                <ion-list class="login-data">
                    <ion-item [class.error]="!name.valid && name.touched">
                        <ion-input type="text" placeholder="Name" [(ngModel)]="registration.name" formControlName="name"></ion-input>
                    </ion-item>


                    <ion-item [class.error]="!email.valid && email.touched">
                        <ion-input  type="text" (blur)="triggerUserId()"  [(ngModel)]="registration.emailId" placeholder="Email"  formControlName="email"></ion-input>
                    </ion-item>

                    <ion-item [class.error]="!userId.valid && userId.touched">
                        <ion-input type="text" placeholder="Username"  [(ngModel)]="registration.userId" formControlName="userId"></ion-input>
                    </ion-item>

                    <!--<ion-item [class.error]="!faculty.valid && faculty.touched">
                        <ion-input type="text" placeholder="Faculty" [(ngModel)]="registration.facultyCode" formControlName="faculty"></ion-input>
                    </ion-item>-->

                    <ion-item>
                        <ion-label>Agreed <span color="primary">Terms & Condition</span></ion-label>
                        <ion-checkbox formControlName="terms"></ion-checkbox>
                    </ion-item>

                </ion-list>

            </ion-card>


            <div *ngIf="name.hasError('required') && name.touched"
                 class="error-box">* {{nameMissing}}
            </div>
            <!--<div *ngIf="!(name.hasError('required')) && name.hasError('pattern') && name.touched"
                 class="error-box">* Name should contain only characters.
            </div>-->
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && email.hasError('required') && email.touched"
                 class="error-box">* {{emailMissing}}
            </div>
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && email.hasError('pattern') && email.touched"
                 class="error-box">* {{emailNotValid}}
            </div>
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !email.hasError('pattern') &&  userId.hasError('required') && userId.touched"
                 class="error-box">* {{userNameMissing}}
            </div>
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !email.hasError('pattern') &&  !userId.hasError('required') && faculty.hasError('required') && faculty.touched"
                 class="error-box">* Please enter faculty code.
            </div>
            <!--<div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !(email.hasError('pattern')) &&  !(userId.hasError('required')) && !(faculty.hasError('required')) && !(faculty.hasError('required'))&& !(terms.hasError('required'))&& terms.touched"-->
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !(email.hasError('pattern')) &&  !(userId.hasError('required')) && !(terms.hasError('required'))&& terms.touched"

                 class="error-box">* {{termsCondMissing}}
            </div>
            <ion-grid>
                <ion-row>
                    <ion-col>
                        <button ion-button block type="button" (click)="back()">Back</button>
                    </ion-col>
                    <ion-col>
                        <button ion-button block type="submit" (click)="userRegistration()"  [disabled]="!signUpForm.valid">Register</button>
                    </ion-col>
                </ion-row>
            </ion-grid>
        </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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