简体   繁体   English

在按键上检查正则表达式的表达

[英]Checking regex expression on keypress

I would like to create my own plugin (without use any external libraries - it's for learning purpose) to validate text typed by user dynamically in regex test function. 我想创建自己的插件(不使用任何外部库-用于学习),以验证用户在regex测试功能中动态键入的文本。

In example I have regex pattern: 在示例中,我有正则表达式模式:

^.{2}$ ^ {2} $

And javascript function 和javascript功能

$('#textbox').bind("keypress", function (event) {
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

Now, I want to type two dots into textbox, but after first keypress is fired, one dot doesn't match to the pattern and nothing happens because event is prevented. 现在,我想在文本框中输入两个点,但是在第一次按下按键后,一个点与模式不匹配,并且由于防止了事件,因此没有任何反应。

My question: Is it possible to check if currently typed text matches with regex pattern? 我的问题:是否可以检查当前键入的文本是否与正则表达式模式匹配?

Your regex only accept two dots (..), but you're testing a single character! 您的正则表达式仅接受两个点(..),但您正在测试一个字符!

var regex = new RegExp("^.{2}$");

$('#textbox').bind("keypress", function (event) {
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

Wanna check current typed text when users finished typing? 要在用户输入完文字后检查当前输入的文字吗? .. Look HERE ..看这里

You can try keydown as it will trigger as soon as you press a key and before character is displayed in textbox. 您可以尝试按下按键,因为按下按键会立即触发此操作,并且在文本框中显示字符之前会触发按键按下。 So if it doesnot match with the pattern you can return out. 因此,如果它与模式不匹配,则可以退出。

$('#textbox').bind("keyup", function (event) {
    var user_input = getElementById ("your_input_id_here");
    if (!regex.test(user_input)) {
        return false;
    }
});

So, essentially you should use onkeyup instead and you should check the whole user input, not just the last key 因此,基本上,您应该使用onkeyup,并且应该检查整个用户输入,而不仅仅是最后一个键

var alpha = /[ A-Za-z]/;
var numeric = /[0-9]/; 
var alphanumeric = /[ A-Za-z0-9]/;

function validateKeypress(validChars) {
    var keyChar = String.fromCharCode(event.which || event.keyCode);
    return validChars.test(keyChar) ? keyChar : false;
}

The HTML will have to change to onkeypress="validateKeypress(alpha);" HTML将必须更改为onkeypress =“ validateKeypress(alpha);”

var in_put = document.getElementById("in_put"),
key = null;

in_put.addEventListener("keydown", match_input);

function match_input(e){

    console.log("Key: "+e.key);
    key = e.key;
    console.log("Match: "+key.match(/a/i));//return array of match
    if(key.match(/a/i)){

        //code on succession.
    }else{

        //code on failure.
    }
}

Note: Change /a/i with your /pattern/ig. 注意:用/ pattern / ig更改/ a / i。 It only check for input is a/A. 它仅检查输入是否为a / A。

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

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