简体   繁体   English

想要通过在用户输入错误时阻止用户在文本字段中输入任何空格

[英]Want to prevent user from entering any space in textfield by providing error when he does

I have a textfield in Extjs. 我在Extjs中有一个文本字段。 This textfield can only contain 此文本字段只能包含

  • Digits 0 - 9
  • Alphabets az or AZ
  • Characters like _ (underscore) and - (hyphen) _ (下划线)和- (连字符)之类的字符

I want to prevent the user from entering anything apart from these characters. 我想防止用户输入除这些字符以外的任何内容。 As such I wish to display an error, something like a red underline along with helptext to notify the user as to why the error is there. 因此,我希望显示一个错误,例如带有红色下划线的helptext以及helptext以通知用户错误原因。

Kindly advice as to how to go about preventing the user from entering anything apart from the above characters and also displaying the error message. 请提供有关如何防止用户输入上述字符以外的内容并显示错误消息的建议。

Use maskRe property: 使用maskRe属性:

An input mask regular expression that will be used to filter keystrokes (character being typed) that do not match. 输入掩码正则表达式,将用于过滤不匹配的击键(正在键入的字符)。 Note: It does not filter characters already in the input. 注意:它不会过滤输入中已经存在的字符。

maskRe: /[A-Za-z0-9\-_]/

Working example: https://fiddle.sencha.com/#fiddle/o4b 工作示例: https : //fiddle.sencha.com/#fiddle/o4b

Something like this. 这样的事情。 There are a whole load of issues with keypress and keydown on different browsers, but I believe this should work on most/all modern browsers without issue. 还有的问题与整个负载keypresskeydown在不同的浏览器,但我相信这应该在大多数/所有现代浏览器的工作没有问题。

 var errorDiv = document.getElementById('error'), testInp = document.getElementById('test'); testInp.addEventListener('keypress', function (evt) { var code = evt.keyCode || evt.charCode; if (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 45 || code === 95) { errorDiv.classList.add('hidden'); } else { evt.preventDefault(); errorDiv.classList.remove('hidden'); } }, false); testInp.addEventListener('keydown', function (evt) { var code = evt.keyCode || evt.charCode; if (code === 8 || code >= 37 && code <= 40|| code === 46) { errorDiv.classList.add('hidden'); } }, false); 
 #error { color: red; } .hidden { visibility: hidden; } 
 <input id="test" type="text" /> <div id="error" class="hidden">As such I wish to display an error, something like a red underline along with helptext to notify the user as to why the error is there.</div> 

You can add an event keyup and check the input key value. 您可以添加事件键盘并检查输入键值。

For example for a space: 例如一个空格:

listeners: {
        keyup: function(field, e) {
             var key = e.getKey(); 
             if (key == 32){
                 alert("Hey dude, what are you doing?");
             }
       }
 }

Or something else. 或者是其他东西。 You can take a look at: 您可以看一下:

field.addClass("x-form-invalid")
field.markInvalid("Hey dude, what are you doing?");

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM