10 November 2018

Custom validator for template driven forms validation

Custom validator

Bước 1: Tạo project Angular 2 bấm vào đây

Bước 2: Tạo directive

ng generate directive testName

test-name.directive.ts
Angular 2+
import {
    Directive,
    forwardRef
} from '@angular/core';
import {
    NG_VALIDATORS,
    AbstractControl,
    ValidatorFn,
    Validator,
    FormControl
} from '@angular/forms';


// validation function
function testNameDirectiveFactory(): ValidatorFn {
    return (c: AbstractControl) => {

        const isValid = c.value === 'TestName';

        if (isValid) {
            return null;
        } else {
            return {
                checkFirstName: {
                    valid: false
                }
            };
        }

    };
}

@Directive({
    selector: '[appTestName][ngModel]',
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: TestNameDirective,
        multi: true
    }]
})
export class TestNameDirective {

    validator: ValidatorFn;

    constructor() {
        this.validator = testNameDirectiveFactory();
    }

    validate(c: FormControl) {
        return this.validator(c);
    }

}
app.module.ts
Angular 2+
import {
    BrowserModule
} from '@angular/platform-browser';
import {
    NgModule
} from '@angular/core';

import {
    AppRoutingModule
} from './app-routing.module';
import {
    AppComponent
} from './app.component';
import {
    TestNameDirective
} from './test-name.directive';
import {
    FormsModule
} from '@angular/forms';
@NgModule({
    declarations: [
        AppComponent,
        TestNameDirective
    ],
    imports: [
        FormsModule,
        BrowserModule,
        AppRoutingModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}
app.component.ts
Angular 2+
import {
    Component
} from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    submitted;

    constructor() {

    }

    onSubmit(value) {
        this.submitted = value;
    }

    onReset() {
        this.submitted = null;
    }
}
app.component.html
Angular 2+
<div class="jumbotron">
    <div class="container">

        <div class="col-md-6 offset-md-3">
            <h4>Custom validator for template driven forms validation</h4>
            <hr class="my-4">

            <form #form="ngForm" (ngSubmit)="form.valid && onSubmit(form.value)">
                <div class="form-group">
                    <label for="my-input">Firstname:</label>
                    <input type="text" #firstname="ngModel" ngModel appTestName name="firstname" required class="form-control" />
                    <div *ngIf="firstname.errors && (firstname.dirty || firstname.touched || form.submitted)" class="text-danger">
                        <p *ngIf="firstname.errors.required">
                            The name is required
                        </p>
                        <p *ngIf="firstname.errors.checkFirstName">
                            Only allowed name is "TestName"
                        </p>
                    </div>
                </div>
                <div class="form-group">
                    <button class="btn btn-success mr-2">Submit</button>
                    <button type="reset" (click)="onReset($event, form)" class="btn btn-danger">reset</button>
                </div>
            </form>

            <div class="alert alert-primary">
                <pre>Is form valid: <br>{{form.valid | json}}</pre>
                <pre>Is form submitted: <br>{{form.submitted | json}}</pre>
                <pre>form value: <br>{{form.value | json}}</pre>
                <pre>firstname.errors: <br>{{firstname.errors | json}}</pre>
            </div>

        </div>
    </div>
</div>

styke.css
/* You can add global styles to this file, and also import other style files */
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css');

ng serve --live-reload




0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang