Angular 5 表单验证(必需)不起作用

标签 angular validation angular5 angular-forms

我正在使用 TypeScript 学习 Angular 5。我对它完全陌生。我现在正在尝试构建一个表单并对其进行验证。但它无法正常工作。

这是我的组件:

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.scss'],
    animations: [routerTransition()]
})
export class LoginComponent implements OnInit {

    loginForm: FormGroup;

    errors = [];

    constructor(private fb: FormBuilder, public router: Router, private globals: GlobalsService, private http: Http) {

    }

    ngOnInit() {
        this.loginForm = new FormGroup({
            email: new FormControl("", Validators.required),
            password: new FormControl("")
        });
    }

    onLoggedin(formData) {
        
        alert("Submit form");
  
  
    }

}

如您所见,我在电子邮件字段上设置了“必需”验证属性。 这是我的 html。

<div class="login-page" [@routerTransition]>
    <div class="row justify-content-md-center">
        <div class="col-md-4">
            <img src="assets/images/logo.png" width="150px" class="user-avatar" />
            <h1>Yo Cash Flow</h1>
            <div class="alert alert-danger" *ngFor="let error of errors">
                <strong>{{ error.msg }}</strong>
            </div>
            <form [formGroup]="loginForm" role="form" (ngSubmit)="onLoggedin(loginForm.value)">
                <div class="form-content">
                    <div class="form-group">
                        <input type="text" name="email" formControlName="email" class="form-control input-underline input-lg" placeholder="Email">
                        <div *ngIf="loginForm.controls['email'].errors.required" class="text-danger">Email is required</div>
                    </div>

 
                </div>
                <button type="submit" class="btn rounded-btn"> Log in </button>
                &nbsp;
                <a class="btn rounded-btn" [routerLink]="['/signup']">Sign up</a>
            </form>
        </div>
    </div>
</div>

如您所见,我正在尝试单独显示错误。我的意思是对于“必需”属性,我正在检索这样的错误消息。必需的。但它不起作用。但是当我尝试像下面这样使用“有效”时,它起作用了。

loginForm.controls['email'].invalid

但我想单独检索错误,因为我想针对不同的错误显示不同的消息。我怎样才能解决这个问题?为什么在我使用 loginForm.controls["email"].errors.required 时它不起作用?针对不同的验证规则显示不同消息的正确方法是什么?

最佳答案

您可以使用 errors 属性,如下所示:

loginForm.controls['email'].errors

如果没有错误,它将返回null,否则将返回一个对象,如下所示:

{ required : true }

然后您只需要创建一个函数来返回人类可读的错误消息,如下所示:

getErrorMessage(controlName, displayName) {
    let result = "";
    let errors  = loginForm.controls[controlName].errors;
    if (errors.required) {
        result += (displayName + " is required.");
    }
    if (errors.whatever) {
        result += "Whatever you like";
    }
    return result;
}

关于Angular 5 表单验证(必需)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48037287/

相关文章:

validation - 验证输入框的输入

angular - 如何修复 Argument of type '"email "' is not assignable to parameter of type ' string[]' 错误?

angular - 如何在 Angular 5 中使用拼接

javascript - Angular4 - 在 JavaScript 文件中使用函数

mysql - 用其他对象的相应名称替换对象 ID

angular - Angular 2/4 的无模态/非模态窗口

php - Laravel Mime 类型验证(KML 文件)

javascript - jQuery 表单验证。如何防止错误消息多次出现

angular - 路由中可变数量的参数

javascript - 在 Angular 5 中基于 JSON 创建动态表