checkForLength(control: FormControl){
console.log(control);
if(control.value.length <= this.charLength && control.value.length > 0){
return {
'lengthError': true
}
}
return null;
}
В данном случае валидатор будет вычислять количество минимальных символов.\\
\\
Далее метод надо передать в массив валидаторов FormControl
pass: new FormControl('', [Validators.required, this.checkForLength.bind(this)]),
для того чтобы не потерять this.charLength, переменная в которой задается минимальное колличество символов, нужно при инициализации валидатора биндить this\\
\\
чтобы отобразить ошибки нужно обратится к контроллу подобным образом
пароль не должен быть пустым!
пароль не должен быть меньше {{charLength}} символов!
В конечном итоге мы получим что то вроде этого\\
\\
import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
answers = [{
type: 'yes',
text: 'Да'
}, {
type: 'no',
text: 'Нет'
}];
form: any;
charLength:number = 4;
ngOnInit() {
this.form = new FormGroup(
{
user: new FormGroup({
email: new FormControl('anchikin@mail.ru', [Validators.email, Validators.required]),
pass: new FormControl('', [Validators.required, this.checkForLength.bind(this)]),
}),
country: new FormControl('ru'),
answer: new FormControl('no')
}
);
}
checkForLength(control: FormControl){
console.log(control);
if(control.value.length <= this.charLength && control.value.length > 0){
return {
'lengthError': true
}
}
return null;
}
onSubmit() {
console.log('Submited!', this.form);
}
}
{{ :angular:angular2:forms:screen7.png |}}