簡體   English   中英

javascript用戶輸入中的正則表達式

[英]regular expression in javascript user input

我在javascript中遇到了正則表達式問題。 我想做的是一個表單寄存器,我必須在其中驗證名字,所以我決定使用javascript驗證(您能告訴我使用js是更好的選擇還是使用ajax php reg驗證?)。 因此,我通過檢查一些教程並從Google閱讀內容來編寫代碼,但是我仍然遇到問題。 它不起作用! 它使用jquery在模糊事件上運行,因此請得到您的幫助。 我要檢查的模式是用戶輸入/ [\\'^£$%&*()} {@#〜?> <>,​​| = _ +] + $ / g中的特殊字符;

這是我的腳本:

                $(document).on('blur','.first_name_input', function() {

                    var firstNameInput = $(".first_name_input").val();

                    if (firstNameInput !== '') {

                        //var exp = /[a-zA-Z0-9-]+$/g;
                        var exp = /[\'^£$%&*()}{@#~?><>,|=_+]+$/g;
                        //if (firstNameInput.test(/^[\'^£$%&*()}{@#~?><>,|=_+-]+$/)) {
                        //if (firstNameInput.match(/[a-zA-Z0-9]*/g)) {
                        if (firstNameInput.match(exp)) {
                            var firstnameValidity = "<div class='name_not_valid_div'>&times; Not allowed characters present!</div>";
                            $('body').prepend(firstnameValidity);
                            $(".name_not_valid_div").hide().fadeIn('slow');

                            if (!errorArray.includes("firstName")){
                                errorArray.push("firstName");
                            }
                        } else {
                            $(".name_not_valid_div").hide();

                            if (errorArray.includes("firstName")){
                                for(var i = errorArray.length - 1; i >= 0; i--) {
                                    if(errorArray[i] === "firstName") {
                                       errorArray.splice(i, 1);
                                    }
                                }
                            }
                        }
                    }

                });

和我的HTML代碼是:

<tr>
                <td class="label">First Name: </td>
                <td class="input"><input type="text" name="first_name" class="input_bar first_name_input" size="30" Placeholder="First Name" /><br/></td>
            </tr>

第一個:使用.trim()避免左/右空格,甚至避免沒有任何字符的空格$(".first_name_input").val().trim();

第二名:驗證

// if the string has special characters
function string_has_spec_char(str){
    var reg = /[~`!#@$%\^&*+=\-\[\]\\';,_./{}\(\)\|\\":<>\?]/g;
    return reg.test(str);
}
// check if string has spaces
function string_has_spaces(str) {
    var reg = /\s/g;
    return reg.test(str);
}

並像這樣使用

if(string_has_spec_char(firstNameInput) === false){
   // the first name doesn't have special characters
}

if(string_has_spaces(firstNameInput) === false){
   // the first name doesn't have spaces
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM