Custom Validation in Angular2 Forms

Following the example given here:

https://angular.io/docs/ts/latest/guide/forms.html

My form looks like this:

<input type="text" class="form-control" id="name"
               required
               [(ngModel)]="model.name" name="name"
               #name="ngModel" >
        <div [hidden]="name.valid || name.pristine" 
             class="alert alert-danger">

I want to add some special validation to this form. I found some tips regarding using the ngFormModel and FormBuilders and Validation classes, however I believe that they are deprecated and are no longer recommended.

( http://almerosteyn.com/2016/03/angular2-form-validation-component )

My question now is how to add custom validation.

In angular 1.x, I used to add functions to ngModel. $ parsers and ngModel. $ formatters pipeline. What is equivalent in angular 2?

+4
source share
1 answer

, , , . :

<form [formGroup]="myForm">
    <label for="id-name">Name</label>
    <input type="text" id="id-name" formControlName="name">
    <label for="id-age">Age</label>
    <input type="text" id="id-age" formControlName="age">
</form>

export class MyComponent implements OnInit {
    myForm:FormGroup;

    ngOnInit() {
        let fuv = FormUtils.validators;

        this.myForm = this.formBuilder.group({
            name: ['', Validators.required],
            age: ['', [Validators.required, fuv.isNumber]],
        });
    }
}

FormUtils

type ValidatorResult = {[key:string]:any};

function _isNumber(control:AbstractControl):ValidatorResult {
    let v = control.value;
    if (isPresent(v) && !isNumber(v) && !isEmptyString(v)) {
        return {'isNumber': false};
    }
    return null;
}

export class FormUtils {
      static validators = {
        isNumber: _isNumber
      }
}

isPresent, isNumber isEmptyString :

isPresent(obj) --> return obj !== undefined && obj !== null;
isNumber(obj) --> return (typeof obj === 'number' && !isNaN(obj));
isEmptyString(obj) --> return obj === '';

Angular 2 : required, minLength, maxLength pattern. . , , _isNumber . (, lessThan), , :

function lessThan(maxVal:number):ValidatorFn {
    return (control:AbstractControl):ValidatorResult => {
        let value = control.value;

        if (isPresent(value) && !isEmptyString(value) && isNumber(value) && parseInt(value) >= maxValue) {
            return {'lessThan': {'maxValue': maxValue, 'actual': value}};
        }

        return null;
    };
}

, ( ) , ( ). , .

+1

Source: https://habr.com/ru/post/1652713/


All Articles