formGroup angular2中的focusout验证

时间:2017-07-22 10:11:28

标签: angular validation angular2-forms angular-forms

我正在尝试在FormGroup中进行focusout验证,但我还没有找到解决方案。请告诉我们是否有可能。我只发现了这种正常的formGroup验证,但我的要求是focusout上的验证。

Component.ts: -

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, FormArray, Validators } 
from '@angular/forms';
import $ from 'jquery';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  addForm : FormGroup;

  constructor(formBuilder: FormBuilder)
  {

    this.addForm = formBuilder.group({
      field_amount : [null, [Validators.required, this.amountValidation]],
      field_reason : [null, Validators.required]
    });
  }

  /****** If amount is 0.00 so does not submit form ******/
  amountValidation(control:FormControl)
  {
    if(control.value == '0.00')
    {
        return {'amountCheck': true};
    }
    return null;
  }

  /****** Set two decimal number ******/
  setTwoNumberDecimal(field_name) {
    let form_name = this.addForm

    let fieldValue = form_name.controls[field_name].value;
    let newValue = parseFloat(fieldValue).toFixed(2);
    if(newValue != 'NaN')
    {
      form_name.controls[field_name].setValue(newValue);
    }
    else
    {
      form_name.controls[field_name].setValue('0.00');
      if(form_name.get(field_name).value == '0.00')
      {
         return {'amountCheck': true};
      }
    }
  }

  /****** Save adjustment values ******/
  save(values:any)
  {
    if(!this.addForm.valid)
    {
      $(".required ").show();
      $('input.ng-invalid, textarea.ng-invalid').first().focus();
    }
    else
    {
      this.dialogRef.close(values);
    }
  }
}

app-component.html: -

<form [formGroup]="addForm" (ngSubmit)="save(addForm.value)">
  <label> Amount</label>
  <div>
    <input id="amount" type="text"  placeholder=" Amount " formControlName = "field_amount" (focusout)="setTwoNumberDecimal('field_amount')">
    <div *ngIf="addForm.controls['field_amount'].hasError('required') " class="required alert alert-danger" style="display: none;">Enter a valid amount.</div>
    <div id="amount-check" *ngIf="addForm.controls['field_amount'].hasError('amountCheck')" class="required alert alert-danger" style="display: none;"> Enter a valid amount. </div>
  </div>

  <label> Reason</label>
  <div>
    <textarea placeholder=" Reason" formControlName="field_reason"></textarea>
    <div *ngIf="addForm.controls['field_reason'].hasError('required') " class="required alert alert-danger" style="display: none;">Enter a valid reason.</div>
  </div>

  <div>
    <button type="submit"> Save </button>
    <button type="button" (click)="dialogRef.close()"> Cancel </button>
  </div>
 </form>

0 个答案:

没有答案