Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

javascript - 在输入字段上复制/粘贴验证并限制字符(Copy/paste validation on input field and restrict character)

I am working on validation of an input control when the user copy paste some value in it(当用户复制一些输入值时,我正在研究输入控件的验证)

On pasting to this input I want to strip out as below:(在粘贴到此输入时,我要剥离如下:) Input can start with underscore or an alphabet(输入可以下划线或字母开头) Input cannot start with number(输入不能以数字开头) Input cannot have any spl character except underscore(输入不能包含任何SPL字符(下划线除外)) Input cannot have spaces(输入不能有空格) This is allowed:(这是允许的:) abc abc_123 _123bcd _123_bcd This is not:(这不是:) 123abc 123_acd abc s22 I tried with the below code:(我尝试了以下代码:) @HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) { this.stripInput(event); } stripInput(event) { setTimeout(() => { this.el.nativeElement.value = this.el.nativeElement.value.replace(/[^A-Za-z ]+/g, '').replace(/s/g, ''); event.preventDefault(); }, 100); } But with above code its not fully working, it doesnt allows: abc_123 _123_ams(但是,由于上面的代码无法完全正常工作,因此它不允许:abc_123 _123_ams) Any inputs please(任何输入请)   ask by karen translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have made a simple over sight with regards to your initial regex.(关于初始正则表达式,您已经做了一个简单的介绍。)

You did not add a start of string check (which is needed to remove numbers and extra special characters at the start of the string).(您没有添加字符串检查开始(需要删除字符串开始处的数字和其他特殊字符)。) You will also need another query if you want to remove other special characters from within the string as well(如果您还想从字符串中删除其他特殊字符,则还需要另一个查询) if you change your last block of code to -(如果您将最后一个代码块更改为-) @HostListener('paste', ['$event']) blockPaste(event: KeyboardEvent) { this.stripInput(event); } stripInput(event) { setTimeout(() => { this.el.nativeElement.value = this.el.nativeElement.value.replace(/^[^A-Za-z_]+/g, '').replace(/[^0-9A-Za-z_]+/g, '').replace(/s/g, ''); event.preventDefault(); }, 100); } It should work as expected (Note the extra ^ at the start of the regex and the added _ to your initial regex as well as the extra following regex).(它应该可以按预期工作(请注意,在正则表达式的开头加上了^ ,并在初始正则表达式和后面的正则表达式中添加了_ )。) What this does pin the search to the start of the string instead of allowing it to act on all parts of the string.(这会把搜索固定到字符串的开头,而不是允许它作用于字符串的所有部分。) It works on your abc_123 _123_ams input and it also strips the extra space in the middle of it as intended.(它可以在您的abc_123 _123_ams输入上工作,并且还会按预期abc_123 _123_ams中间多余的空间。) (it makes it abc_123_123_ams )((它使abc_123_123_ams ))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...