[英]Combining result (ORing) of 2 validators in Angular and using it as single validating factor
I want to get a validation result on a form field by ORing the 2 validation results我想通过 ORing 2 个验证结果来获取表单字段的验证结果
eg例如
this.registerForm = this.formBuilder.group({
username: ['', [Validators.required,Validators.pattern(USERNAME_REGEX) || Validators.email]],
});
Is something like this possible?这样的事情可能吗?
Constraints: THE USERNAME SHOULD BE EITHER AN EMAIL ADDRESS OR SHOULD BE A VALID USERNAME WHICH MATCHES TO THE PATTERN OF USERNAME'S REGEX限制条件:用户名应该是电子邮件地址或应该是匹配用户名正则表达式模式的有效用户名
I want to use angular's inbuilt email validators' output and the output of a custom made regex pattern to identify whether the field is valid or not.我想使用 angular 的内置电子邮件验证器的输出和自定义正则表达式模式的输出来识别该字段是否有效。
PS: I have refered this post -> Angular 2 combined form validation but it does not match my condition PS:我参考了这篇文章 -> Angular 2 组合表单验证,但它不符合我的条件
You need to write your own validator function.您需要编写自己的验证器函数。
private loginNameValidator = (): ValidatorFn => {
const userNameValidator = Validators.pattern(USERNAME_REGEX);
return (control: AbstractControl): ValidationErrors | null => {
const userNameInvalid = userNameValidator(control);
if (!userNameInvalid) {
return null;
}
const emailInvalid = Validators.email(control);
if (!emailInvalid) {
return null;
}
return { loginNameInvalid: true };
};
};
Use it用它
this.registerForm = this.formBuilder.group({
username: ['', [Validators.required, this.loginNameValidator()]],
});
There is no in built function which meets your requirements.没有内置功能可以满足您的要求。
You will have to implement a custom validator for this.您必须为此实现自定义验证器。
public userNameOrEmailValidator(): ValidatorFn => {
return (control: AbstractControl): ValidationErrors | null => {
const userNameRegex = // TODO: define username regex here.
const emailRegex = // TODO: define email regex here.
const isValid = userNameRegex.test(control.value) || emailRegex .test(control.value);
return !isValid? {inValidUserName: true} : null;
};
}
Call it like this:像这样调用它:
this.registerForm = this.formBuilder.group({
username: ['', [Validators.required, userNameOrEmailValidator()]],
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.