Email validation to allow 2 domains

Discussion in 'Web Design and Development' started by ombrenelcielo, Aug 25, 2011.

  1. ombrenelcielo, Aug 25, 2011
    Last edited by a moderator: Aug 26, 2011

    ombrenelcielo macrumors regular

    ombrenelcielo

    Joined:
    Jan 21, 2011
    Location:
    Helsinki, Finland
    #1
    Hi everyone,
    I needed to create a validation form to allow only 2 domains (basic check if @abd.com or @asd.com and allow those only).

    It's plain javascript, can you give me some suggestions?

    :confused:

    as of today I do the validation like this:

    PHP:
    function validateForm()
    {
    var 
    x=document.getElementById("user_email").value;
    var 
    atpos=x.indexOf("@thisdomain.com");
    var 
    dotpos=x.lastIndexOf(".");
    if (
    atpos<|| dotpos<atpos+|| dotpos+2>=x.length)
      {
      
    alert("Please use Your @thisdomain.com email address");
      return 
    false;
      }
    }
     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    Here's a tweaked function that uses a regular expression to check for two domains being present. In this case the valid domains are thatdomain.com and thisdomain.com. It also ensures that there are at least 2 characters before the @ characters and no spaces anywhere. I added an else piece simply for testing purposes.

    PHP:
    function validateForm() {
        var 
    document.getElementById("user_email").value;
        var 
    regex = new RegExp(/^[\w\.\+_-]+[\w]+@(this|that)domain\.com$/);
        
    // Validate email address
        
    if (!regex.test(x)) {
            
    alert("Please use your @thisdomain.com or @thatdomain.com email address.");
            return 
    false;
        }
        else {
            
    alert('Address valid.');
        }
    }
     
  3. jtara macrumors 65816

    Joined:
    Mar 23, 2009
    #3
    Of course you realize that Javascript client-side validation is no validation at all, right?

    It's a nicety. You still need server-side validation.
     
  4. ombrenelcielo thread starter macrumors regular

    ombrenelcielo

    Joined:
    Jan 21, 2011
    Location:
    Helsinki, Finland
    #4
    thanks for the infos,
    I have a script running server side to clean up the domains different than the ones I want from the DB, and JS on the client side helps a bit to have more coherent data ;) :)
     

Share This Page