angular2 - 验证后添加错误类

时间:2016-12-30 09:14:34

标签: angular angular2-template

我已经搜索了很多但是无法按预期工作。 所以我有表单验证器,用于检查电子邮件是否有效并设置 emailValid 。如果它无效,我想将 has-error 类添加到表单组。问题是,只有在初始状态下将 emailValid 设置为false时,才会添加类 has-error 。所以我只能在开头添加类,但不能在电子邮件验证后继续。

在HTML模板中

<div class="form-group label-floating" [class.has-error]="!emailValid">

在组件中

let mail_regex = new RegExp("^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$");

this.emailValid = mail_regex.test(this.model.email);

虽然这部分使用相同的变量 emailValid 但它的工作正常。所以我真的很困惑。

<p *ngIf="!emailValid" i18n><strong>Email is not valid.</strong> Please write valid email.</p>

感谢您的回答。

整个组件

import { Component, OnInit } from '@angular/core';

import { User } from '../models/user';
import { UserService } from '../user.service'


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

  private errorMessage;
  private successMessage;

  private repeatPassword;

  private emailValid;
  private emailNotExists;
  private passwordValid;
  private passwordEqual;
  private firstnameValid;
  private lastnameValid;

  private notValid;
  private repairErrors;

  constructor(private userService: UserService) {
    this.notValid = false;
    this.emailValid = true;
    this.emailNotExists = true;
    this.passwordValid = true;
    this.passwordEqual = true;
    this.firstnameValid = true;
    this.lastnameValid = true;
    this.repairErrors = false;

  }


  ngOnInit(){}

  private model = new User('', '', '', '', '', '');

  onSubmit() {
    this.emailValidator();
    this.passwordValidator();
    this.firstnameValidator();
    this.lastnameValidator();

    if(!this.notValid) {
      this.userService.createUser(this.model)
      .subscribe(res => this.successMessage = res.code == '201', error =>  this.errorMessage = <any>error);

      this.repairErrors = false
    }
    else {
      this.repairErrors = true
    }


  }

  emailValidator() {
    //check if exists
    if (this.model.email.length > 1){
      this.userExists();
    }

    //check if valid
    let mail_regex = new RegExp("^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$");

    this.emailValid = mail_regex.test(this.model.email);

    this.notValid = !(this.emailValid && this.emailNotExists &&
      this.passwordValid && this. passwordEqual &&
      this.firstnameValid && this.lastnameValid);
    console.log(this.notValid)
  }

  passwordValidator(){
    this.passwordValid = this.model.password.length > 5 && this.model.password.length < 78;
    this.passwordEqual = this.model.password == this.repeatPassword

    this.notValid = !(this.emailValid && this.emailNotExists &&
      this.passwordValid && this. passwordEqual &&
      this.firstnameValid && this.lastnameValid);
  }

  firstnameValidator(){
    let name_regex = new RegExp('^[a-zA-Z ]+$');
    this.firstnameValid = name_regex.test(this.model.firstname) && this.model.firstname.length > 1;

    this.notValid = !(this.emailValid && this.emailNotExists &&
      this.passwordValid && this. passwordEqual &&
      this.firstnameValid && this.lastnameValid);
  }

  lastnameValidator(){
    let name_regex = new RegExp('^[a-zA-Z ]+$');
    this.lastnameValid = name_regex.test(this.model.lastname) && this.model.lastname.length > 1;

    this.notValid = !(this.emailValid && this.emailNotExists &&
      this.passwordValid && this. passwordEqual &&
      this.firstnameValid && this.lastnameValid);
  }


  userExists() {

    if (this.model.email != '') {
      this.userService.getUser(this.model.email).subscribe(
                      res => this.emailNotExists = res.code == '0',
                      error => this.errorMessage = <any>error);
    }
  }

}

HTML

<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12 col-md-offset-3 col-lg-offset-3">
<div *ngIf="errorMessage" class="alert alert-dismissible alert-danger">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <p i18n><strong>Error on server. </strong>Please try again or contact administrator</p>
</div>
<div *ngIf="successMessage" class="alert alert-dismissible alert-success">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <p i18n><strong>Success. </strong>Please check your email and activate your account.</p>
</div>
<div *ngIf="notValid" class="alert alert-dismissible alert-warning">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <p *ngIf="!emailNotExists" i18n><strong>Email exists.</strong> Please choose another email or login.</p>
    <p *ngIf="!emailValid" i18n><strong>Email is not valid.</strong> Please write valid email.</p>
    <p *ngIf="!passwordValid" i18n><strong>Password is not valid.</strong>It should be at least 6 characters long.</p>
    <p *ngIf="!passwordEqual" i18n><strong>Passwords are not equal.</strong> Write passwords again.</p>
    <p *ngIf="!firstnameValid" i18n><strong>First name is not valid.</strong> It should be at least 2 characters long and contains only letters.</p>
    <p *ngIf="!lastnameValid" i18n><strong>Last name is not valid</strong> It should be at least 2 characters long and contains only letters.</p>
</div>
<div class="well bs-component">
        <legend>
            <h1 class="text-primary" i18n="Sign up form">Sign up</h1>
        </legend>
    <form class="form-horizontal">
        <fieldset>
            <div class="col-xs-10 col-md-10 col-sm-10 col-lg-10 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-offset-1">
                <div class="form-group label-floating" [class.has-error]="!emailValid">
                    <label for="name" class="control-label" i18n>Email</label>
                    <input type="text" class="form-control" (change)="emailValidator()" [(ngModel)]="model.email" [ngModelOptions]="{standalone: true}" id="username">
                </div>
                <div class="form-group  label-floating">
                    <label for="password1" class="control-label" i18n>Password</label>
                    <input type="password" class="form-control" [(ngModel)]="model.password" [ngModelOptions]="{standalone: true}" id="password1">
                </div>
                <div class="form-group  label-floating">
                    <label for="password2" class="control-label" i18n>Confirm password</label>
                    <input type="password" class="form-control" (change)="passwordValidator()" [(ngModel)]="repeatPassword" [ngModelOptions]="{standalone: true}" id="password2">
                </div>
                <div class="form-group  label-floating">
                    <label for="name" class="control-label" i18n>First name</label>
                    <input type="text" class="form-control" (change)="firstnameValidator()" [(ngModel)]="model.firstname" [ngModelOptions]="{standalone: true}" id="firstname">
                </div>
                <div class="form-group  label-floating">
                    <label for="lastname" class="control-label" i18n>Last name</label>
                    <input type="text" class="form-control" (change)="lastnameValidator()" [(ngModel)]="model.lastname" [ngModelOptions]="{standalone: true}" id="lastname">
                </div>
                <div class="form-group  label-floating">
                    <label for="company" class="control-label" i18n>Company</label>
                    <input type="text" class="form-control" [(ngModel)]="model.company" [ngModelOptions]="{standalone: true}" id="company">
                </div>
                <div class="form-group  label-floating">
                    <label for="country" class="control-label" i18n>Country</label>
                    <input type="text" class="form-control" [(ngModel)]="model.country" [ngModelOptions]="{standalone: true}" id="country">
                </div>
            </div>
            <div class="col-md-offset-3">
                <button type="submit" class="col-md-8 btn btn-raised btn-primary" (click)="onSubmit()" i18n>Sign up</button>
            </div>
        </fieldset>
    </form>
</div>
<div *ngIf="repairErrors" class="alert alert-dismissible alert-danger">
    <button type="button" class="close" data-dismiss="alert">×</button>
    <p i18n><strong>Cannot submit.</strong> Please repair your errors first.</p>
</div>

3 个答案:

答案 0 :(得分:0)

这是使用角度2表单验证的错误方法,但即使你想这样做,你也必须创建一个函数,它将在输入更改时被调用,你将传递输入的值并调用:

Collection

this.emailValid = mail_regex.test(this.model.email);

答案 1 :(得分:0)

创建一个这样的自定义验证器:

export class PatterValidator {
    public static patternValidator ( pattern ) {
            return ( c ) => {
                if ( pattern ) {
                    if ( ! c.value || new RegExp(pattern ).test( c.value ) ) {
                        return null;
                    }
                    return {
                        pattern : {
                            text : '<strong>Email is not valid.</strong> Please write valid email.' 
                        }
                    };
                }
                return null;
            };
        }

}

并将其添加到您的控件中:

        let yourPattern = "^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$";

        let validators = Validators.compose( [
            PatterValidator.patternValidator(yourPattern),
            anyOtherValidator ...
        ] );
        emailControl.setValidators( validators );

然后您可以在模板中使用它,如:

<p *ngIf="!emailValid" i18n [innerHtml]="emailValid.errors.pattern.text"></p>

答案 2 :(得分:0)

发现问题。它适用于我的自定义CSS类,但不适用于 Material Design for Bootstrap 。原因是它在您使用浮动标签时会覆盖自己当前的类。因此,如果我使用自己的类,它可以正常工作:例如: CSS
.selected{ background-color: #1a1a1a; }
HTML

[ngClass]="{'selected': emailValid}


[class.selected]="emailValid"