Angular 5 form validation (required) not working

浪子不回头ぞ 提交于 2019-12-05 22:43:50

You can use the errors property, like so:

loginForm.controls['email'].errors

If there are no errors, it will return null, otherwise it will return an object like so:

{ required : true }

Then you simply need to create a function that will return a human readable error message, like so:

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;
}
Aayush

You must use (loginForm.valid) inside the *ngIf or [disabled] property of the button. This automatically checks whether the form is validated or not from the ts file.

Moreover, inside the ts file, you can write your validations:

new FormControl('',[Validators.required])

like this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!