4

I have created a form with validation checking using,

import { FormGroup, Validators, FormControl } from "@angular/forms";

Currently I have the Submit button [disabled] till the form is filled out correctly. The only way I am showing the user if the form is valid or not is by showing red in the input when the form field is not valid.

enter image description here

I would like to display an error message to the user to show them what is wrong.

Is there something built into Angular2 to show the error message or why the input field is not valid? Or do I need to built custom error messages for each form field? If so how would I go about checking each input field, let's say when someone leaves focus from the respective field. So if they leave the input field and it was not valid then I can display a message telling them it was not valid and why?

I have a method to show the message I just need to come up with a way to obtain and error message. In other words produce the text from the form on why it is not valid.

Example

Please provide a valid mobile number

Code

REGEX

  ngOnInit() {
        this.personalForm = new FormGroup({
            email : new FormControl(this.auth.user.email,Validators.required ),
            first_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),
            middle_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),

            last_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),

            dob : new FormControl (null, [
                Validators.required,
                Validators.pattern("[1][9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[2][0][0-9][0-9]-[0-9][0-9]-[0-9][0-9]")
            ]),
            mobile_phone: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),
            home_phone: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),

            business_phone: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),
            fax_number: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ]),
            ssn: new FormControl(null, [
                Validators.required,
                Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
            ])
        });
    }

Valid Boolean / Handle The Form Data

save(model: Personal, isValid: boolean) {
        if (!isValid) {
            console.log('Personal Form is not valid');
            console.log(model, isValid);
        } else {
            console.log('Personal Form is valid');
            console.log(model, isValid);
            let headers = new Headers();
            headers.append('Content-Type', 'application/json');
            return this.http
                .post('http://localhost:4200/api/updateProfile',
                    model,
                    {headers: headers})
                .map((res: Response) => res.json())
                .subscribe((res) => {
                    //do something with the response here
                    console.log(res);
                });
        }
    }

Form

<form [formGroup]="personalForm" novalidate (ngSubmit)="save(personalForm.value, personalForm.valid)">
    <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12">
            <div class="card card-inverse card-success">
                <div class="card-header">
                    <strong>Personal Information</strong>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="form-group col-sm-12 col-md-12">
                            <label for="email">Email</label>
                            <div class="input-group">
                                <span class="input-group-addon"><i class="fa fa-envelope"></i>
          </span>
                                <input type="text" class="form-control" id="email" formControlName="email" placeholder="{{personal.email}}"readonly>
                            </div>
                            <div class="alert alert-danger" *ngIf="!personalForm.controls.email.valid && submitted ">
                                *Email is required.
                            </div>
                        </div>
                    </div>
5
  • This can all be handled in the HTML template. Can you please post your form template. Commented Dec 5, 2016 at 3:24
  • I added a piece of the form so you could se.e Commented Dec 5, 2016 at 3:33
  • I think I see how I can control this know making custom errors. But the most information I can get from the form the better. I guess to save myself time. Please see this line !personalForm.controls.middle_name.valid && submitted Notice the controls. is this built in to FormControl? SO I can call each object in the FormControls I built? I am doing that right correct? Commented Dec 5, 2016 at 3:37
  • You are doing it correctly. That's what I was getting at with wanting to see your template. Yes, it's built into FormGroup/FormControl. Commented Dec 5, 2016 at 3:44
  • Well do you see in my save() method I have a boolean? Do I need to use that boolean to check each input for error client side? I still cant even get the alerts to show up. So a few things I need to be clear on, is controls built in? So I am accessing it right? personalForm.controls.first_name ?? Is not? I saw a tutorial use that and it made sense it was built in but I have not see it in the docs. Commented Dec 5, 2016 at 3:46

1 Answer 1

1

Summary

To access the FormGroup input fields you can use syntax to access the controls you have created.

this.FormGroupName.get('ControlName').status

That will return VALID or INVALID

In my case this is how it was done,

Example

Import correct packages,

import {FormGroup, Validators, FormControl } from "@angular/forms";
import {INVALID, VALID} from "@angular/forms/src/model";

Create FormGroup,

personalForm: FormGroup;

Create FormControl,

 ngOnInit() {
        this.personalForm = new FormGroup({
            first_name: new FormControl(null,[
                Validators.required,
                Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
            ]),
   });
}

Add the FormControlName to the form and the function to call when you want the error to be checked.

<input (blur)="firstNameValidate('*First Name Required', 'Use 1-30 letters to spell your name.')" type="text" class="form-control" placeholder="Enter first name" id="first_name" formControlName="first_name">

Check for VALID or INVALID,

firstNameValidate(ErrorTitle, ErrorMessage) {
        if (this.personalForm.get('first_name').status == VALID) {
            this.getSuccess("First Name Entered", "First name entered correctly");
        } else {
            this.toastWarning(ErrorTitle, ErrorMessage);
        }
    }

Calling Errors

In my case I decided to show my errors in a toast. So I used blur to track when the user leaves an input field. When the user moves out of an input field the firstNameValidate() function is called and the correct toast is displayed based on the value, VALID or INVALID. Depending on the response one of these two functions is fired off.

toastWarning(ErrorTitle, ErrorMessage) {
        var toastOptions:ToastOptions = {
            title: ErrorTitle,
            msg: ErrorMessage,
            showClose: true,
            timeout: 7000,
            theme: 'bootstrap',
            onAdd: (toast:ToastData) => {
                console.log('Toast ' + toast.id + ' has been added!');
            },
            onRemove: function(toast:ToastData) {
                console.log('Toast ' + toast.id + ' has been removed!');
            }
        };
            this.toastyService.warning(toastOptions);
        }

    getSuccess(SuccessTitle, SuccessMessage) {
        var toastOptions:ToastOptions = {
            title: SuccessTitle,
            msg: SuccessMessage,
            showClose: true,
            timeout: 5000,
            theme: 'bootstrap',
            onAdd: (toast:ToastData) => {
                console.log('Toast ' + toast.id + ' has been added!');
            },
            onRemove: function(toast:ToastData) {
                console.log('Toast ' + toast.id + ' has been removed!');
            }
        };
        this.toastyService.success(toastOptions);
    }

Then the user sees the correct toast / message,

Success

enter image description here

Warning

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.