Angular 2


Angular2 Custom Validations All Versions

2.0.0-rc.0
2.0.0-rc.1
2.0.0-rc.2
2.0.0-rc.3
2.0.0-rc.4
2.0.0-rc.5
2.0.0-rc.6
2.0.0-rc.7
2.0.0
2.0.1
2.0.2
2.1.0
2.2.0
2.3.0
2.4.1

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 0

    Angular 2 has two kinds of custom validators. Synchronous validators as in the first example that will run directly on the client and asynchronous validators (the second example) that you can use to call a remote service to do the validation for you. In this example the validator should call the server to see if a value is unique.

    export class CustomValidators {
    
    static cannotContainSpace(control: Control) {
        if (control.value.indexOf(' ') >= 0)
            return { cannotContainSpace: true };
    
        return null;
    }
    
    static shouldBeUnique(control: Control) {
        return new Promise((resolve, reject) => {
            // Fake a remote validator.
            setTimeout(function () {
                if (control.value == "exisitingUser")
                    resolve({ shouldBeUnique: true });
                else
                    resolve(null);
            }, 1000);
        });
    }}
    

    If your control value is valid you simply return null to the caller. Otherwise you can return an object which describes the error.

  • 0
       constructor(fb: FormBuilder) {
        this.form = fb.group({
            firstInput: ['', Validators.compose([Validators.required, CustomValidators.cannotContainSpace]), CustomValidators.shouldBeUnique],
            secondInput: ['', Validators.required]
        });
    }
    

    Here we use the FormBuilder to create a very basic form with two input boxes. The FromBuilder takes an array for three arguments for each input control.

    1. The default value of the control.
    2. The validators that will run on the client. You can use Validators.compose([arrayOfValidators]) to apply multiple validators on your control.
    3. One or more async validators in a similar fashion as the second argument.
Please consider making a request to improve this example.

Syntax

Syntax

Parameters

parameterdescription
controlThis is the control that is being validated. Typically you will want to see if control.value meets some criteria.

Remarks

Remarks

Still have a question about Angular2 Custom Validations? Ask Question

Topic Outline