Improve custom validation rules

This commit is contained in:
mauriziovitale84
2016-09-07 16:14:53 +01:00
parent 19f66fdb64
commit 3ec32f216a
2 changed files with 35 additions and 7 deletions

View File

@@ -39,14 +39,16 @@ export class LoginDemoComponent implements OnInit {
constructor(public router: Router) {
this.customValidation = {
username: ['', Validators.compose([Validators.required, Validators.minLength(8), , Validators.maxLength(10)])],
username: ['', Validators.compose([Validators.required, Validators.minLength(4), Validators.maxLength(15)])],
password: ['', Validators.required]
};
}
ngOnInit() {
this.alfrescologin.addCustomValidationError('username', 'minlength', 'Username must be at least 8 characters.');
this.alfrescologin.addCustomValidationError('username', 'required', 'LOGIN.MESSAGES.USERNAME-REQUIRED');
this.alfrescologin.addCustomValidationError('username', 'minlength', 'LOGIN.MESSAGES.USERNAME-MIN');
this.alfrescologin.addCustomValidationError('username', 'maxlength', 'Username must not be longer than 11 characters.');
this.alfrescologin.addCustomValidationError('password', 'required', 'LOGIN.MESSAGES.PASSWORD-REQUIRED');
}
onLogin($event) {

View File

@@ -16,7 +16,7 @@
*/
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { FORM_DIRECTIVES, ControlGroup, FormBuilder } from '@angular/common';
import { FORM_DIRECTIVES, ControlGroup, FormBuilder, Validators } from '@angular/common';
import {
AlfrescoTranslationService,
AlfrescoPipeTranslate,
@@ -88,11 +88,16 @@ export class AlfrescoLoginComponent implements OnInit {
translate.addTranslationFolder('node_modules/ng2-alfresco-login/dist/src');
this.initFormError();
this.initFormMessages();
this.initFormFieldsMessages();
}
ngOnInit() {
this.form = this._fb.group(this.fieldsValidation);
if (this.hasCustomFiledsValidation()) {
this.form = this._fb.group(this.fieldsValidation);
} else {
this.initFormFieldsDefault();
this.initFormFieldsMessagesDefault();
}
this.form.valueChanges.subscribe(data => this.onValueChanged(data));
}
@@ -232,9 +237,19 @@ export class AlfrescoLoginComponent implements OnInit {
}
/**
* Default form messages values
* Init form fields messages
*/
private initFormMessages() {
private initFormFieldsMessages() {
this._message = {
'username': {},
'password': {}
};
}
/**
* Default form fields messages
*/
private initFormFieldsMessagesDefault() {
this._message = {
'username': {
'required': 'LOGIN.MESSAGES.USERNAME-REQUIRED',
@@ -246,6 +261,13 @@ export class AlfrescoLoginComponent implements OnInit {
};
}
private initFormFieldsDefault() {
this.form = this._fb.group({
username: ['', Validators.compose([Validators.required, Validators.minLength(4)])],
password: ['', Validators.required]
});
}
/**
* Disable the error flag
*/
@@ -259,4 +281,8 @@ export class AlfrescoLoginComponent implements OnInit {
private enableError() {
this.error = true;
}
private hasCustomFiledsValidation(): boolean {
return this.fieldsValidation !== undefined;
}
}