Angular 2表单验证
场景:
如果用户尝试在输入类型=" text"中输入特殊字符,应该阻止输入?
特殊字符不应出现在相应的文本框中?
答案 0 :(得分:0)
代码,如下所示修复了插入位置问题
1.将事件类型更改为'(输入)'在主持人听众中
2.在类中定义插入符的开始和结束位置,它解决了问题
@Directive({
selector: '[ngModel][maskSpecialCharacter]',
host: {
'(ngModelChange)': 'onInputChange($event)',
'(input)': 'onInputChange($event.target.value, true)'
}
})
export class SpecialCharacterMask {
constructor(public model: NgControl, public ele: ElementRef, public render: Renderer) { }
onInputChange(event, backspace) {
var position = this.ele.nativeElement.selectionStart;
var value = event.replace(/[!$%^&*()+|~=`{}\[\]:";#@'<>?,.\/\\]/gi, '');
this.render.setElementProperty(this.ele.nativeElement, "value", value);
this.ele.nativeElement.selectionEnd = position;
}
}
答案 1 :(得分:0)
您可以创建自定义验证器
import { FormControl } from '@angular/forms'
export function restrictedWords(words) {
return (control: FormControl): { [key: string]: any } => {
if (!words) return null
var invalidWords = words.map(w => control.value.includes(w) ? w : null)
.filter(w => w != null)
return invalidWords && invalidWords.length > 0
? { 'restrictedWords': invalidWords.join(', ') }
: null
}
}
从表单中调用自定义验证程序函数,
this.textBox1 = new FormControl('',[Validators.required, Validators.maxLength(400), restrictedWords(['foo','bar'])])
答案 2 :(得分:0)
角反应形式的方法:
需要以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
答案 3 :(得分:0)
尝试将模式用作
this.form= this.fb.group({
name: ['', [Validators.pattern('[a-zA-Z0-9 ]')]],
});