简体   繁体   中英

How to validate string with RegExp()

I have a problem that I want to validate input field using RegExp() . Allows entering digits, characters and special character "_" to get the last string: regex3_example . When pressing the space key, "_" will be displayed. Hope everybody help please. Thank you!

document.querySelector('#input').addEventListener('input', function () {
    var text = this.value;

    if (re.test(text)) {
        console.log("Valid");
    } else {
        console.log("Invalid");
    }
    $(document).keypress(function (event) {
        if (event.keyCode === 32) {
            var re = new RegExp("^[a-zA-Z_]");
            var insert_string = text+'_';
            let insert_text = insert_string.trim();
            $('#key').val(insert_string);
        }
    });
});

I don't use jquery, but i can help. If you don't need to process your input data but only validade for user, you can use the prop pattern in your HTML tag.

<input 
  type="text" 
  pattern="\w*_\w{1,}"
  title="Try the pattern test_test"/>

In this case, when you click on Button submit, the page will prenvent this action and show in this input the message passed on the prop title .

Hope help you, see ya!

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