在Angular中,可以通过自定义验证器来实现对表单输入的自定义验证。下面是一个示例的解决方法:
function passwordValidator(control: FormControl): {[key: string]: any} | null {
const password = control.value;
const hasUpperCase = /[A-Z]+/.test(password);
const hasNumber = /[0-9]+/.test(password);
if (!hasUpperCase || !hasNumber) {
return { 'passwordStrength': true };
}
return null;
}
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
'password': new FormControl('', Validators.compose([
Validators.required,
passwordValidator
]))
});
}
}
在上面的示例中,我们将自定义验证器函数passwordValidator
应用到密码输入框的FormControl对象上,并在模板中使用myForm.get('password').hasError('passwordStrength')
来判断是否需要显示错误信息。
这样,当用户输入的密码不符合自定义验证器的要求时,将会显示相应的错误信息。