对于反应性表单验证,我观察到了许多教程和柱塞链接,但我没有得到任何解决我的问题的站点。
问题1: formgroup组模式是[aA-zZ0-9'-]$/)](允许no,字符,-,',空格特殊字符)
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('')])
});
}
}以上请检查此柱塞链接。
https://plnkr.co/edit/km7nGR8DjyE4l6tH5JEC?p=preview
在这里,如果您观察到name字段,它在某些情况下是按照正则表达式条件工作的。
**case1-> aa -- not valid(minimum 3 characters),
case2-> aaa@ --not valid(special chararacter)
case3-> aaa@b -- valid(not giving any message)**在上面的case1中,如果您遵守case3输入,即使它不满足区域规则,也没有抛出任何信息,我不确定我的团队是否正确,我的要求是(min-3, max-10, allow no, characters, -,', space special charactes)。
我尝试了这么多类型,但每一个地方我都遇到同样的问题。
problem2:如何为表单数组应用自定义验证器
请给我最好的方法,这将适用于所有通用用例。
提前感谢
苏米亚
发布于 2019-02-21 10:27:41
关于数组验证,如果要验证数组的大小,可以构建如下所示的自定义验证:
arrayLengthValidator(minimumLength: number): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
if (control.value.length < minimumLength) {
return {'arrayLength': 'array length is invalid'};
}
return null;
};
}然后在表单中添加如下内容:
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))
});现在,如果要检查数组元素上的空值,可以使用验证作为指令,并将选择器添加到输入中:
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;
}
}在投入方面:
<input type="text" appEmptyValue>发布于 2018-02-20 13:05:19
对于第三种情况,模式是/^[a-zA-Z0-9-']*$/。
对于您的请求(min-3,最大-10,允许否,字符,-,',空格特殊字符)=使用此模式,如果您不需要@或$只是删除该/^[a-zA-Z0-9-' !@#$%^&]*$/
https://stackoverflow.com/questions/48500169
复制相似问题