Reputation: 342
For reactive form validations i observed many tutorials and plunker links but i am not getting any site which solves my problem
problem 1: formgroup pattern is
[aA-zZ0-9'-]$/)]
(allow no, characters, -,', space special charactes)
export class AppComponent implements OnInit {
private myForm: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.myForm = this.fb.group({
'name': ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern(/[aA-zZ0-9'-]$/)]],
'phoneNumbers': new FormArray([new FormControl('')])
});
}
}
for above that please check this plunker link
https://plnkr.co/edit/km7nGR8DjyE4l6tH5JEC?p=preview
Here if you observed name field it's working as per regular expression conditions in some cases
**case1-> aa -- not valid(minimum 3 characters),
case2-> aaa@ --not valid(special chararacter)
case3-> aaa@b -- valid(not giving any message)**
in above sceanarios case1, 2 is fine if you observe case3 input even it's not satisfiying regix rule it's not throwing any message
I am not sure that my regix is right, my requirment is (min-3, max-10, allow no, characters, -,', space special charactes)
I am trying so many types, but every where i am getting same problem
problem2: How to apply custom validator for form arrays
Please give me best approach which will sutes all general use cases
Thanks in advance
Soumya
Upvotes: 1
Views: 5110
Reputation: 167
Regarding array validation, if you want to validate the size of the array, you can build a custom validation like this:
arrayLengthValidator(minimumLength: number): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
if (control.value.length < minimumLength) {
return {'arrayLength': 'array length is invalid'};
}
return null;
};
}
And then just add to your form like this:
this.myForm = this.fb.group({
'name': ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern(/[aA-zZ0-9'-]$/)]],
'phoneNumbers': this.formBuilder.array([], this.arrayLengthValidator(1))
});
Now if you want to check empty values on array elements, you can use validation as a Directive and add the selector to your input:
import { Directive } from '@angular/core';
import { Validator, NG_VALIDATORS, AbstractControl } from '@angular/forms';
@Directive({
selector: '[appEmptyValue]',
providers: [{provide: NG_VALIDATORS, useExisting: EmptyValueDirective, multi: true}]
})
export class EmptyValueDirective implements Validator {
validate(control: AbstractControl): {[key: string]: any} | null {
return control.value === '' ? {'emptyValue': 'input value cannot be empty'} : null;
}
}
And on the input:
<input type="text" appEmptyValue>
Upvotes: 1
Reputation: 206
For case three the pattern is /^[a-zA-Z0-9-']*$/
.
For your requirment (min-3, max-10, allow no, characters, -,', space special charactes) = use this pattern if you don't need @ or $ just remove that /^[a-zA-Z0-9-' !@#$%^&]*$/
Upvotes: 0