在角度2中显示自定义无效消息

时间:2018-05-03 05:08:37

标签: angular angular-reactive-forms

我的表格正在运作。它可以检测有效和无效的输入字段。我需要做的是显示我的自定义验证"密码无效"如果输入字段无效。请参阅下面的代码,了解.html和.ts

<form [formGroup]="subscriptionForm">
    <h3 style="color: gray; text-align: center;">Registration</h3>

    <div class="row">
    <div class="col-md-6">
        <div class="md-form">
        <i class="fa fa-user prefix grey-text"></i>
        <input type="text" formControlName="UserName" id="UserName" class="form-control" placeholder="Enter Username">
        <!-- <label for="UserName">Your UserName</label> mdbInputDirective-->
        <div style="color: gray" *ngIf="subscriptionForm.get('UserName').hasError('required') && subscriptionForm.get('UserName').touched" >
            Username is required.
        </div>
        </div>
        <br>
        <div class="md-form">
        <i class="fa fa-user prefix grey-text"></i>
        <input type="text" formControlName="FirstName" id="FirstName" class="form-control" placeholder="Enter Firstname">
        <!-- <label for="FirstName">Your First name</label> -->
        </div>
    </div>
    <div class="col-md-6">
        <div class="md-form">
        <i class="fa fa-user-secret prefix grey-text"></i>
        <input type="password" id="Password" formControlName="Password" class="form-control" placeholder="Enter Password">
        <!-- <label for="Password">Your password</label> -->
        </div>
        <div style="color: gray" *ngIf="subscriptionForm.get('Password').hasError('required') && subscriptionForm.get('Password').touched" >
            Password is required.
        </div>
        <div style="color: gray" *ngIf="!subscriptionForm.get('Password').hasError('valid') && subscriptionForm.get('Password').dirty" >
            Password is invalid.
        </div>
    </div>
    </div>

</form>

constructor(private fb: FormBuilder) { }

ngOnInit() {
this.subscriptionForm = this.fb.group({
    UserName: [null, Validators.required],
    Password: [null, Validators.required],
    Email: [null, Validators.required],
    FirstName: [null, Validators.required],
    LastName: [null, Validators.required]
});
this.resetForm();
}

1 个答案:

答案 0 :(得分:0)

您没有任何有效错误的验证工具,让我们尝试添加一个正则表达式验证工具来检查密码是否有某些标准

         stamp          |       avg        
------------------------+------------------
 2018-05-01 00:00:00+02 |             12.3
 2018-05-01 01:00:00+02 |           14.775
 2018-05-01 02:00:00+02 | 17.9333333333333
 2018-05-01 03:00:00+02 | 16.8333333333333
 2018-05-01 04:00:00+02 |             16.9
(5 rows)

在html模板中,只需将有效更改为模式

this.subscriptionForm = this.fb.group({
    UserName: [null, Validators.required],
    Password: [null, [Validators.required,Validators.pattern('[A-Za-z]{8,}')],
    Email: [null, Validators.required],
    FirstName: [null, Validators.required],
    LastName: [null, Validators.required]
});