简体   繁体   中英

jquery regular expression allow anything

Hi I have a search box on my Rails app and at the moment I have this:

var searchReg = /^([a-zA-Z0-9]{0,16})$/; 

which works fine for everything except I cannot search for an email entry. I have tried looking everywhere or even accept any character at all once it has at least 2 characters in the box. I've tried putting in +@ in random places but to be honest I don't have a clue what i'm doing. Could somebody please help me.

Code from comments:

jQuery(function(){
    $("input[value='Search']" ).click(function(){
        $(".error").hide();
        var hasError = false;
        var searchReg = /^([a-zA-Z0-9]{0,16})$/;
        var searchVal = $("#q").val();
        if(searchVal == '') {
            $("#q").after('<span class="error">Please enter a search term.</span>');
            hasError = true;
        } else if(!searchReg.test(searchVal)) {
            $("q").after('<span class="error">Enter valid text.</span>');
            hasError = true;
        }
        if(hasError == true) {return false;}
    }); 
}); 

You can simply add each symbol to the character class, making sure to escape those that have a special significance:

var searchReg = /^([a-zA-Z0-9@\-_\.]{0,16})$/; 

A powerful tool to figure out regexps is: http://regex101.com/

PS: If you input your regexp there you will notice you have a capturing group that is probably unnecessary.

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