如何验证提交时的反应形式?

时间:2018-09-18 06:27:46

标签: angular forms validation ionic3 angular-reactive-forms

我正在为我的应用程序使用反应式表单,我想在提交时验证表单,但我无法做到这一点。这是我的代码,任何人都可以让我知道我在做错或丢失的事情。

这是我的表单生成器

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ViewController,LoadingController, Events,AlertController } from 'ionic-angular';
import {Validators, FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { MyinfoService} from '../../../../providers/app-services/myinfo/myinfo.service';

private formBuilder: FormBuilder) {
      this.licenseinfo = navParams.get('licenseinfo');
      this.startDate = this.licenseinfo.dlIssued_date;
      this.expiryDate= this.licenseinfo.dlExpiry_date;
      console.log(this.startDate);
      this.todo = this.formBuilder.group({
        issued_state  : ['', Validators.required],
        license_no    : ['', Validators.required],
        name          : ['', Validators.required],
        status        : ['Pending'],
        issued_date   : ['',Validators.required],
        expiry_date   : ['',Validators.required],
        address_line1 : ['',Validators.required],
        address_line2 : [''],
        city          : ['',Validators.required],
        zipcode: ['',Validators.required],
        state  : ['',Validators.required],
        employee_id   : ['']
      });
    }

这是我的表格

<ion-header>

    <ion-navbar>
      <ion-buttons start>
        <button ion-button (click)="dismiss()">Close</button>
      </ion-buttons>
      <ion-title>License Info Edit</ion-title>
    </ion-navbar>

  </ion-header>


  <ion-content padding>  
    <form [formGroup]="todo" (ngSubmit)="saveMyinfoLicenseinfo()">
      <ion-item>
        <ion-label stacked class="requiredLabel"> State Issued By</ion-label>
        <ion-input value="{{licenseinfo.issued_state}}" formControlName="issued_state"></ion-input>
      </ion-item> 

      <ion-item>
        <ion-label stacked class="requiredLabel">Driver Lic. No</ion-label>
        <ion-input type="text" value="{{licenseinfo.driver_lic_no}}" formControlName="license_no"></ion-input>
      </ion-item>

      <ion-item>
        <ion-label stacked class="requiredLabel">Name on DL</ion-label>
        <ion-input value="{{licenseinfo.name}}" formControlName="name"></ion-input>
      </ion-item>

      <ion-item>
        <ion-label stacked class="requiredLabel">Date Issued</ion-label>
        <ion-datetime displayFormat="MMM DD, YYYY" pickerFormat="DD MMM YYYY" formControlName="issued_date" [(ngModel)]="startDate" ></ion-datetime>
      </ion-item>

      <ion-item>
        <ion-label stacked class="requiredLabel">Expiry Date</ion-label>
        <ion-datetime displayFormat="MMM DD, YYYY" pickerFormat="DD MMM YYYY" formControlName="expiry_date" [(ngModel)]="expiryDate" ></ion-datetime>
      </ion-item>

      <ion-item>
          <ion-label stacked class="requiredLabel">Address Line1</ion-label>
          <ion-input value="{{licenseinfo.address_line1}}" formControlName="address_line1"></ion-input>
        </ion-item>

      <ion-item>
          <ion-label stacked >Address Line2</ion-label>
          <ion-input value="{{licenseinfo.address_line2}}" formControlName="address_line2"></ion-input>
        </ion-item>
      <ion-item>
          <ion-label stacked class="requiredLabel">City</ion-label>
          <ion-input value="{{licenseinfo.city}}" formControlName="city"></ion-input>
        </ion-item>

      <ion-item>
          <ion-label stacked class="requiredLabel">State</ion-label>
          <ion-input value="{{licenseinfo.issued_state}}" formControlName="issued_state"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked class="requiredLabel">Zipcode</ion-label>
          <ion-input value="{{licenseinfo.zipcode}}" formControlName="zipcode"></ion-input>
        </ion-item>

      <ion-input value="{{employee_id}}" formControlName="employee_id" hidden></ion-input>
      <ion-row>
        <ion-col>
          <button ion-button type="button" color="dark" outline block margin-top (click)="dismiss()">Cancel</button>
        </ion-col>
        <ion-col>
          <button ion-button type="submit" color="dark" margin-top block>Save</button>
        </ion-col>
      </ion-row>
    </form>
  </ion-content>

这是我的“提交”代码:

saveMyinfoLicenseinfo(){
    if(this.todo.valid){
    let loading = this.loadingCtrl.create({});
    loading.present();
    this.myinfoService.saveLicenseDetails(this.todo.value).subscribe(data => {
      loading.dismiss();        
        if(data.isSuccessful){
          this.viewCtrl.dismiss(true);
        }
        else
          this.viewCtrl.dismiss(false);
      });
      this.submitted = true;
    }
    else{
      this.validateAllFields(this.todo);
    }
}
validateAllFields(formGroup: FormGroup) {         
  Object.keys(formGroup.controls).forEach(field => {  
      const control = formGroup.get(field);            
      if (control instanceof FormControl) {             
          control.markAsTouched({ onlySelf: true });
          console.log(3);
      } else if (control instanceof FormGroup) {        
          this.validateAllFields(control);  
          console.log(this.validateAllFields(control));
      }
  });
}

所以我在此函数上调用onsubmit,如果表单无效,那么我试图使所有的领域都受到感动,但是即使提交后,领域的颜色也不会改变。我知道这是正确的方法吗?还是有更好的方法呢?

3 个答案:

答案 0 :(得分:0)

您以错误的方式定义了验证器,请查阅官方文档以Form Validation为您提供帮助

正确的方法是:

document.addEventListener('DOMContentLoaded', () => {
    document.querySelector("#submit").onclick = (event) => {
        const li = document.createElement('li');
        li.innerHTML = document.querySelector('#message').value;
        document.querySelector('#add-message').append(li);
        event.preventDefault();
        // note the lines added here ↓↓↓
        li.addEventListener('click', function() {
                console.log('You have clicked', this.textContent);
            });
        // add an item into the second list
        const li2 = document.createElement('li');
        li2.innerHTML = document.querySelector('#message').value;
        document.querySelector('#add-message2').append(li2);
        event.preventDefault();
        li2.addEventListener('click', function() {
            console.log('You have clicked', this.textContent);
        });
    };

    // and don't forget the loop here ↓↓↓
    for (let li of document.querySelectorAll("#add-message li, #add-message2 li")) {
        // here ↓↓↓ you should add event listeners to list items one by one
        li.addEventListener('click', function() {
            console.log('You have clicked', this.textContent);
        });
    }

});

答案 1 :(得分:0)

您的无效表单字段在提交时不会更改颜色,因为您似乎没有为具有无效值的字段设置任何CSS(或CSS类)。

在Angular文档的Reactive form validation部分中查看示例:

  1. 如何获取有关模板中每个字段有效性的信息,
  2. 如何添加HTML以在表单旁边/之内显示错误(如果需要)

The ngClass directive对于动态地将特定的类分配给无效的表单字段可能非常有帮助。然后,您可以在随附的CSS文件中编码适当的CSS,或利用Ionic可能专门为无效表单条目提供的任何类。

答案 2 :(得分:0)

尝试使用此HTML代码。

A AND B AND C AND D