比较2个输入字段的值,通过模板验证Angular 7中的表单

比较2个输入字段的值,通过模板验证Angular 7中的表单,angular,typescript,angular-validation,Angular,Typescript,Angular Validation,我进入Angular 7的第一周,我一直在使用基于模板的基本验证在我的项目中执行基本表单,但我现在需要验证表单,因为一个字段的值必须高于另一个字段的值 我已经尝试在component controller中使用这些值本身,但是虽然我能够确认这些值是否有效,但我无法使用此代码向用户说明问题所在 if (issueThresholdForm.value.lowScore > issueThresholdForm.value.highScore) { // Show user error

我进入Angular 7的第一周,我一直在使用基于模板的基本验证在我的项目中执行基本表单,但我现在需要验证表单,因为一个字段的值必须高于另一个字段的值

我已经尝试在component controller中使用这些值本身,但是虽然我能够确认这些值是否有效,但我无法使用此代码向用户说明问题所在

if (issueThresholdForm.value.lowScore > issueThresholdForm.value.highScore) {
  // Show user error
  // This is the messing part, I guess
}
这是我正在使用的模板

<div *ngIf="_issueCategory">
  <form (submit)="submitIssueThreshold(issueThresholdForm)" #issueThresholdForm="ngForm">
    <mat-form-field class="half-width" floatLabel="always">
      <mat-label [translate]="'issueThreshold.modals.highScore'"></mat-label>
      <input name="highScore" type="number" matInput placeholder="0" [(ngModel)]="_issueCategory.highScore"
        required #highScore="ngModel">
    </mat-form-field>
    <mat-form-field class="half-width" floatLabel="always">
      <mat-label [translate]="'issueThreshold.modals.lowScore'"></mat-label>
      <input name="lowScore" type="number" matInput placeholder="0" [(ngModel)]="_issueCategory.lowScore"
        required #lowScore="ngModel">
    </mat-form-field>
    <mat-form-field class="full-width" floatLabel="always">
      <mat-label [translate]="'issueThreshold.modals.description'"></mat-label>
      <textarea name="description" matInput [(ngModel)]="_issueCategory.thresholdDescription">
            </textarea>
    </mat-form-field>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal" [translate]="'modal-confirm.cancel'"></button>
      <button type="submit" class="btn btn-primary primary" [disabled]="issueThresholdForm.invalid || issueThresholdForm.pristine" [translate]="'modal-confirm.submit'"></button>
    </div>
  </form>
</div>

您可以按如下方式在中使用

HTML

<div>
  <form [formGroup]="myForm">

    <label>Low Score: </label>
    <input formControlName="lowScore" type="number">
    <br/><br/>
    <label>High Score: </label>
    <input formControlName="highScore" type="number">

    <div>
      <span style="color: red" *ngIf="myForm.get('highScore').touched && myForm.get('highScore').hasError('higherThan')">High score should be higher than lower score.</span>
    </div>

  </form>
</div>
找到工作。

您可以在中使用,如下所示

HTML

<div>
  <form [formGroup]="myForm">

    <label>Low Score: </label>
    <input formControlName="lowScore" type="number">
    <br/><br/>
    <label>High Score: </label>
    <input formControlName="highScore" type="number">

    <div>
      <span style="color: red" *ngIf="myForm.get('highScore').touched && myForm.get('highScore').hasError('higherThan')">High score should be higher than lower score.</span>
    </div>

  </form>
</div>
找到工作。

编辑:

使用相同的解决方案以反应方式编辑。因此,创建表单组并添加附加到表单组的自定义验证器:

\u issueCategory={lowScore:1,highcore:2};
issueThresholdForm:FormGroup;
构造函数(私有fb:FormBuilder){
this.issueThresholdForm=this.fb.group({
highScore:[此._issueCategory.highScore,[验证器.必需]],
lowScore:[此._issueCategory.lowScore,[验证器.required]]
},{validators:validateScore})
}
验证程序功能:

导出功能验证核心(
控件:抽象控件
):ValidationErrors | null{
if(控制和控制.get(“高分”)和控制.get(“低分”)){
const highscore=control.get(“highscore”).value;
const lowscore=control.get(“lowscore”).value;
返回(低分数>高分数){scoreError:true}:null
}
返回null;
}
然后您可以删除ngModel(很重要!),因为它们不应该与反应形式混合。此外,您还可以删除表单的所有验证,如
required
,因此最终输入可以简单地如下所示:



原件:

我非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常非常。您可以更好地控制表单,正如Nithin Kumar Biliya在评论中提到的,单元测试更容易

话虽如此

这里是一个使用模板驱动表单的解决方案,因为这是您当前正在使用的

您可以创建一个附加到表单标记的指令,该指令内部有一个验证器,用于比较highscore和lowscore的值,并将错误附加到表单,或者返回
null
(在表单中被视为有效)。因此,验证程序将如下所示:

import{Directive}来自“@angular/core”;
进口{
抽象控制,
NG_验证器,
验证器,
验证错误
}从“@angular/forms”;
@指示({
选择器:“[scoreValidation]”,
供应商:[
{
提供:NG_验证器,
useExisting:ScoreValidator指令,
多:真的
}
]
})
导出类ScoreValidator指令实现验证器{
构造函数(){}
//这里的控件是formgroup
验证(控件:AbstractControl):ValidationErrors | null{
if(控制和控制.get(“高分”)和控制.get(“低分”)){
//表单控件及其值
const highscore=control.get(“highscore”).value;
const lowscore=control.get(“lowscore”).value;
//无效,返回一个错误
如果(低分>高分){
返回{scoreError:true};
}
//有效的
返回null;
}
//表单控件尚不存在,返回null
返回null;
}
}
将该指令添加到appmodule中的declarations数组中,并通过将该指令附加到form标记来使用它:


可以使用
*ngIf=“issueThresholdForm.hasError('scoreError')

编辑:

使用相同的解决方案以反应式方式编辑。因此,请创建表单组并添加附加到表单组的自定义验证器:

\u issueCategory={lowScore:1,highcore:2};
issueThresholdForm:FormGroup;
构造函数(私有fb:FormBuilder){
this.issueThresholdForm=this.fb.group({
highScore:[此._issueCategory.highScore,[验证器.必需]],
lowScore:[此._issueCategory.lowScore,[验证器.required]]
},{validators:validateScore})
}
验证程序功能:

导出功能验证核心(
控件:抽象控件
):ValidationErrors | null{
if(控制和控制.get(“高分”)和控制.get(“低分”)){
const highscore=control.get(“highscore”).value;
const lowscore=control.get(“lowscore”).value;
返回(低分数>高分数){scoreError:true}:null
}
返回null;
}
然后,您可以删除ngModel(很重要!),因为它们不应该与反应式表单混合。您还可以删除表单的所有验证,如
required
,因此最终输入可以简单地如下所示:



原件:

强烈地,强烈地建议,他们一开始可能会感到困惑,但完全值得。您可以更好地控制表单,正如Nithin Kumar Bilya在评论中提到的,单元测试更容易

话虽如此

这里是一个使用模板驱动表单的解决方案,因为这是您当前正在使用的

您可以创建一个附加到表单标记的指令,该指令中有一个验证器,用于比较highscore和lowscore的值,并将错误附加到表单,或者返回
null
(在表单中被视为有效)。因此,验证器如下所示:

import{Directive}来自“@angular/core”;
进口{
抽象控制,
NG_验证器,
验证器,
<p class="text-danger" [hidden]="(lowerScore.value > higerScore.value ? false: true) || (lowScore.pristine && !issueThresholdForm.submitted)">
                    The lower scrore can not be greater than higer score
</p>