DAndre Ealy
DAndre Ealy

Reputation: 53

Validating email using js

I trying to create this form that only allows people to submit an email that is using a @msu.edu email. I have the alert that is coming up when it's not a msu.edu email, but when I use an email like [email protected] its not submitting the form.

function checkMail() {
    var email = document.validation.email.value.toLowerCase();
    var filter = /^([\w-]+(?:\.[\w-]+)*)@msu.edu/i;
    var result = filter.test(email);
    alert('Valid email found: ' + result);
    return result;
}

Upvotes: 0

Views: 116

Answers (4)

Saurabh Chauhan
Saurabh Chauhan

Reputation: 144

This will do it

put this function onclick event of button and change getelementById's Id with your TextBox Id and this will give you alert "msu.edu"

     function checkMail() 
      {
        var email = document.getElementById("email").value.toLowerCase();
        var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\                  [[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; ;
      if (regex.test(email)) 
        {
          var temp = email.substring(email.lastIndexOf("@")+1);
          if (temp != "msu.edu") 
          {
              alert("Enter correct email");
          }

      }

  }

Upvotes: 0

Jackcob
Jackcob

Reputation: 317

why not try this

bool IsValidEmail(string email)
{
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch {
        return false;
    }
}

Upvotes: 0

Sanjay Bhimani
Sanjay Bhimani

Reputation: 1603

Format in just like this... var filter = /^([\w-]+(?:\.[\w-]+)*)@msu\.edu/i; as per Gaurang said. It works.

Upvotes: 1

Gaurang Tandon
Gaurang Tandon

Reputation: 6753

You need to escape the . there.

Correct code:

function checkMail() {
    var email = document.validation.email.value.toLowerCase();
    var filter = /^([\w-]+(?:\.[\w-]+)*)@msu\.edu/i;
    //                                       ^-- escape this dot
    var result = filter.test(email);
    alert('Valid email found: ' + result);
    return result;
}

Demo

Upvotes: 3

Related Questions