2009-12-10 45 views
1

我需要在我的asp.net mvc(C#)應用程序中使用jQuery實現正則表達式。jquery正則表達式與自定義消息

我有一個形式的標誌,其中我需要驗證所需的正則表達式的字段。

說得更清楚一點,我的登錄表單中有UsernamePassword字段。我需要首先驗證,如果用戶輸入任何值,那麼我需要驗證正則表達式。

例如:如果輸入無效值,Username必須至少爲5個字符,並且不能包含特殊字符。它應該說Please enter a valid Username with atleast 5 characters and no special characters

密碼必須最少5個字符,ATLEAST特殊字符,1個數字,如果輸入無效值,應該說Please enter a valid password with atleast 5 characters and should contain one numer and special character

所以我需要給自定義消息爲每個所需和正則表達式中的字段。

是否有常用的插件或函數用於jquery中的正則表達式?

回答

1

找到共同的直線前進方法的實現在SO:

$.validator.addMethod(
    "regex", 
    function(value, element, regexp) { 
     if (regexp.constructor != RegExp) 
      regexp = new RegExp(regexp); 
     else if (regexp.global) 
      regexp.lastIndex = 0; 
     return this.optional(element) || regexp.test(value); 
    }, 
    "Please check your input."); 

它可以用作:

 $('#signinForm').validate({ 
      rules: { 
       Username: { 
        required: true, 
        regex: "YOURREGULAREXPRESSION" 
       } 
      }, 
      messages: { 
       Username: { 
        required: "Enter the Username", 
        regex: "Enter the valid Username" 
       } 
      } 
     }); 

因此,我們可以具有自定義消息多個自定義驗證(正則表達式)。

1

你不會在jQuery中做正則表達式。它內置於JavaScript本身。當然,還有一些使用正則表達式的jQuery驗證插件。

退房:http://docs.jquery.com/Plugins/Validation

大多數這些插件應該讓你輸入自定義消息顯示,如果它不驗證。

2

用戶名:

/^\w{5,}$/五個或更多字字符(az,AZ,0-9和下劃線)

密碼:

/^(?=.*\d)(?=.*[a-z])(?=_|\W).{5,}$/i至少五個字符的最小一位數字的字符串,一個字母表(不區分大小寫)和一個特殊字符。