简体   繁体   中英

Block user from input with regex

I have a function which checks an input box with an regex string for max. 3 words and two spaces.

    $('input.words_input__input_field').on("keyup", function(e) {
     if (e.keyCode == 13) {
         send_message();
     }
    var re = /^((([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*)){3}$/g;
    var str = $('input.words_input__input_field').val();
    var m;
    while ((m = re.exec(str)) !== null) {
        if (m.index === re.lastIndex) {
            re.lastIndex++;
        }
        send_text = str;
        // View your result using the m-variable.
        // eg m[0] etc.
    }
    console.log(m);
    });

When the Regex applies on the input value the send_text will not be edited anymore. But I want to prevent the user from typing anymore into the input box.

Is there any way to create a block for the input so that the user cannot type in more than as "allowed" by the regex?

EDIT: I have some problems with this regex, so it works too perfect it should only prevent the user from typing in after three words and two spaces are in the input field. I have a code like this:

var test = /^((([\'\-\+\s]\s*[a-zA-Z])?[a-zA-Z]*)){3}$/g;
if (test.test($(this).val())) {
    $(".input").val($(".input").val().replace(/\s/g, ""));
}

But it "kills" all whitespaces. And I only want to delete the whitespaces at the end. Any ideas?

Set the input to disabled with

$('input.words_input__input_field').prop('disabled', true);

Or store the .val() in a variable or a data object as long as it's valid and regenerate it from there if the regex is not met anymore.

EDIT:

The code below will let the user type 3 words, separated by commas. If anything is added that violates the regex, the input will be reset to the last value.

var p;
var f;
$(".inp").on('keyup',function(e){
    var k = e.which;
    var i = $(".inp").val();

    if(k != 8 && k != 46){ // allow backspace and delete
        if(i.search(/^[A-Za-z]+ [A-Za-z]+ [A-Za-z]+$/) >= 0){
            f = true;
            p = i;
        }
        else{
            if(f){
                $(".inp").val(p);    
            }
        }
    }
});

<input type="text" class="inp">

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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