Angular2 - 使用自定义Validator比较两个控件值

时间:2017-07-19 12:23:33

标签: validation angular2-forms custom-validators angular2-formbuilder

我需要使用自定义验证器验证两个表单控件值。它应该使用formbuilder来完成。

curl -F "file=@temp.txt" https://server.com

这里我需要添加自定义验证器,其中fromTotal和tototal应该相等。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分: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}; 
    }
  }
}