【问题标题】:Working on Angular 2 form validation. How to prevent the user entering the special character in to the input text box?处理 Angular 2 表单验证。如何防止用户在输入文本框中输入特殊字符?
【发布时间】:2016-10-22 13:36:18
【问题描述】:

Angular 2 表单验证

场景:

如果用户尝试在输入类型=“文本”中输入特殊字符,是否应该阻止输入?

特殊字符不应该出现在相应的文本框中?

【问题讨论】:

  • @Sanket,验证模式会动态变化,但我的输入控件行为不应允许用户输入为该控件提到的模式
  • 这种方法可能对你有用stackoverflow.com/questions/37800841/…
  • @GünterZöchbauer 上述方法效果很好。现在我面临着带有验证掩码的插入符号位置的问题。当我在输入[type =“text”]中键入一些字符串时。使用该验证掩码指令,我尝试用匹配的模式替换输入字符串。场景:当我尝试从输入[type =“text”]中输入的字符串中间(将插入符号位置放在字符串之间)进行编辑时,插入符号位置移到最后。它不允许在字符串中间进行更改。
  • 对不起,不知道。也许是别人。一个可以复制的 Plunker 也可能会有所帮助。

标签: angular angular2-forms


【解决方案1】:

代码,如下所示修复插入符号位置问题
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;
}
}

【讨论】:

    【解决方案2】:

    您可以创建自定义验证器,

    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'])])
    

    【讨论】:

      【解决方案3】:

      尝试使用模式作为

       this.form= this.fb.group({
              name: ['', [Validators.pattern('[a-zA-Z0-9 ]')]],
       });
      

      【讨论】:

        【解决方案4】:

        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

        【讨论】:

          猜你喜欢
          • 2016-01-06
          • 2015-09-13
          • 1970-01-01
          • 2016-02-14
          • 1970-01-01
          • 1970-01-01
          • 2019-07-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多