Angular 5 form validation (required) not working

拥有回忆 提交于 2019-12-12 09:48:18

问题


I am learning Angular 5 with TypeScript. I am completely new to it. I am now trying to construct a form and validating it. But it is not working properly. Please see my code below.

This is my component.

@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");


    }

}

As you can see I am setting "required" validation attribute on the email field. This is my 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>

As you can see I am trying to show the error individually. I mean for "required" attribute, I am retrieving the error message like this errors.required. But it is not working. But when I tried to use "valid" like below, it is working.

loginForm.controls['email'].invalid

But I want to retrieve the error individually because I want to show the different message for the different error. Please how can I fix this? Why it is not working when I use "loginForm.controls["email"].errors.required"? What is the correct way of showing the different message for the different validation rule please?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/48037287/angular-5-form-validation-required-not-working

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