2010-04-13 106 views
2

我有一個網站需要用戶登錄。客戶只會從其公司的域中獲得訪問權限。我需要根據電子郵件域地址驗證字段。即。只允許來自@ mycompany.com的電子郵件地址通過。驗證基於特定域的電子郵件字段

這可以通過jquery.validate插件完成嗎?我看到你可以檢查它是否是有效的電子郵件,但我想確保它匹配特定模式(@ mycompany.com)。

任何幫助,將不勝感激!

回答

3

只需使用jQuery的驗證做一個字符串比較檢查電子郵件與預期域結束。

這樣你知道電子郵件看起來有效,是必需的域。

以下是檢查域的可能方法。這實際上並不需要jQuery。

/** 
* Checks that the user's email is of the correct domain. 
* 
* userInput: potential email address 
* domain: Correct domain with @, i.e.: "@mycompany.com" 
* Returns: true iff userInput ends with the given domain. 
*/ 
function checkDomain(userInput, domain) { 
     // Check the substring starting at the @ against the domain 
     return (userInput.substring(userInput.indexOf('@')) === domain; 
} 
+0

感謝本, 我很新jQuery的。你有關於如何編寫比較代碼的建議嗎?謝謝! – 2010-04-13 16:28:40

+0

我已經添加了一個功能,可以完成我使用普通JavaScript描述的功能。 – 2010-04-13 17:20:50

+0

實際上應該返回userInput.substring(userInput.indexOf('@'))===域; 你有一個太多的關閉。 – 2018-01-28 04:45:12

0
In this example my domain is "@uol.edu.pk". You can do it like this. 


    $(document).ready(function (e) { 
       $('#SubmitButton').click(function() { 
        var email = $('#form-email').val(); 
        // Checking Empty Fields 
        if ($.trim(email).length == 0 || $("#form-first-name").val() == "" || $("#form-password").val() == "" || $("#Password1").val()=="") { 
         alert('All fields are Required'); 
         e.preventDefault(); 
        } 
        if (validateEmail(email)) { 
         alert('Good!! your Email is valid'); 
        } 
        else { 
         alert('Invalid Email Address'); 
         e.preventDefault(); 
        } 
       }); 
      }); 
      // Function that validates email address through a regular expression. 
      function validateEmail(pEmail) { 
       var filterValue = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; 
       if (filterValue.test(pEmail)) { 
        if (pEmail.indexOf('@uol.edu.pk', pEmail.length - '@uol.edu.pk'.length) != -1) 
        { 
         return true; 
        } 
        else { 
         alert("Email Must be like([email protected])"); 
         return false; 
        } 
       } 
       else 
       { 
        return false; 
       } 
      } 
    enter code here