Angular 反应形式的方法:
需要在表单Validation中添加一个Validator。
此外,下面的正则表达式不适用于国际化。请根据需要更改正则表达式。
this.form= this.formBuilder.group({
name: ['', [ Validators.required, Validators.pattern(/^[a-zA-Z0-9!@#$%^&*()]+$/)] ],
description: ['']
});
请注意,Validators.pattern 方法不需要引号
方法 2
export function isSecuredInput(input: string): boolean {
const tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
const tagOrComment = new RegExp(
'<(?:'
// Comment body.
+ '!--(?:(?:-*[^->])*--+|-?)'
// Special "raw text" elements whose content should be elided.
+ '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*'
+ '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*'
// Regular name
+ '|/?[a-z]'
+ tagBody
+ ')>',
'gi');
return input.search(tagOrComment) === -1 ? true : false;
}
形式的变化:
isValidInput(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
if (!isNullOrUndefined(control.value)) {
return isSecuredInput(control.value.toString()) ? null : { invalid: true};
}
return null;
};
}
表格是
this.form = this.formBuilder.group({
name: new FormControl('', {
validators: [Validators.required, this.isValidInput()],
updateOn: 'change'
})
})
来源 isSecure 来自Sanitize/Rewrite HTML on the Client Side