0

我需要使用自定義驗證程序驗證兩個窗體控件值。它應該使用formbuilder完成。Angular2 - 使用自定義驗證程序比較兩個控制值

Component.ts 

    this.mainForm = this.fb.group({ 
     fromtotal: [0, [Validators.Required]], 
     toTotal: [0, [Validators.Required]], 
     option: [value, Validators.required] 
    }); 

在這裏我需要添加自定義驗證器,其中fromTotal和tototal應該是相等的。

回答

0

試試這個:

<div class="form-group"> 
     <label for="">Password</label> 
     <input type="password" class="form-control" name="password" [ngModel]="user.password" 
     required **validateEqual="confirmPassword"** reverse="true" #password="ngModel"> 
    </div> 
    <div class="form-group"> 
     <label for="">Retype password</label> 
     <input type="password" class="form-control" name="confirmPassword" [ngModel]="user.confirmPassword" 
     required **validateEqual="password"** reverse="false" #confirmPassword="ngModel"> 
    </div> 
+0

我需要自定義驗證程序來做到這一點。 – user2401393

0

嘗試:

// import here your EqualsValidator 
import { EqualsValidator} from '...'; 

... 
... 
... 

this.mainForm = this.fb.group({ 
    fromtotal: [0, [Validators.Required]], 
    toTotal: [0, [Validators.Required]], 
    option: [value, Validators.required] 
}, {validator: EqualsValidator.equals('fromtotal', 'toTotal')}); 

equals.validator.ts:

import { FormGroup } from '@angular/forms'; 

export class EqualsValidator { 

    /** 
    * compares 2 values 
    * */ 
    static equals(valueControlNameA: string, valueControlNameB: string) { 
    return (group: FormGroup): {[key: string]: any} => { 
     // get values 
     let valueA = group.get(valueControlNameA).value; 
     let valueB = group.get(valueControlNameB).value; 

     return valueA === valueB ? null : {equals: true}; 
    } 
    } 
}