-3

I have to make an email validation that an Email address must start with a string followed by '@', followed by another string with Javascript.

Can someone show me how please?

I used this code but it gives me an error if I use a dot sign only not for every single character.

var email=document.forms["subscriptionForm"]["email"].value;
var atCharacter = email.indexOf("@"); 
var dotCharacterAfterAt = email.indexOf('.', atCharacter + 1); 
var dotLastCharacter=email.indexOf('.', atCharacter - 1);
var dotPosition=email.lastIndexOf(".");

if (atCharacter < 1 || dotPosition < atCharacter+2 || dotPosition + 2 >= email.length) {/* I got this code from http://www.w3schools.com/js/js_form_validation.asp */
    alert("Incorrect E-Mail address");
    return false;
}
    if (email[0] == '.'){
    alert("You can't enter a dot character as a first character")
    return false
    }

    if (email==null || email=="") { 
        alert("E-Mail must be filled out !");
        return false;   
    } 
    if(atCharacter + 1 == dotCharacterAfterAt){
        alert("You must enter a string after the @ sign");
        return false;
    }

    if (atCharacter - 1 == dotLastCharacter){
        alert("You must not enter a string before the @ sign in your address"); 
        return false;
    }

    if (dotPosition == email.length - 1) {
        alert("You must not enter a dot as a last character in your address");/* an error will occur and tells you that you must not enter a "." character as a last character in your address*/
        return false;
    }
DannyFar94
  • 67
  • 9
  • possible duplicate of [Validate email address in JavaScript?](http://stackoverflow.com/questions/46155/validate-email-address-in-javascript) – Nateowami Sep 10 '14 at 05:26
  • possible duplicate of [Using a regular expression to validate an email address](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Konstantin Dinev Sep 10 '14 at 05:26
  • 1
    Short answer: no. Long answer: no you don't, you need to sort-of-kind-of validate the email client side, but you **REALLY** need to verify it server side, because that's where it's going to actually matter, and you're not going to write your own code for it, you want to use an established library to do that. As a comment in addition to all the duplicate questions. – Mike 'Pomax' Kamermans Sep 10 '14 at 05:26

4 Answers4

0
var email = 'string@string';

/[^@]+@[^@]+/.test(email); // returns true;

The above does exactly what you've asked. However, I don't think what you've asked is enough to validate an email address. I would suggest just using the validator library as follows:

<script type="text/javascript" src="validator.min.js"></script>
<script type="text/javascript">
  validator.isEmail('foo@bar.com'); //=> true
</script>

This library does much more than just an email validation which you might find useful.

esengineer
  • 9,514
  • 7
  • 45
  • 69
  • Just copy/paste as it is shown above and it will work. If you expect an email to be entered in the input field which has an `id="email"`, then you can do `var email = document.getElementById('email').value`. – esengineer Sep 10 '14 at 05:42
0
var email_pat=/^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/;

        //id is the email text box id
        var val=$('#'+id).val();
        if(val.match(email_pat)==null && val!='')
            $('#'+id).addClass('error');

This should work.

amit_183
  • 961
  • 3
  • 19
  • 36
0

Try this simple piece of code:

var email = prompt('Enter your Email');
var re = /[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if (email == '' || !re.test(email))
{
    alert('Invalid email address.');
}
else {
    alert('Thank You, the email is valid!');
}

DEMO here

Abdul Jabbar
  • 2,573
  • 5
  • 23
  • 43
-1

This will return true for any string that contains exactly one @ somewhere in the middle of it:

function could_be_email_address(email) {
    return email.split('@').length >= 2;
}

Honestly, that's all you need to do. A valid email address can contain ANYTHING before the @ per the RFC:

the local-part MUST be interpreted and assigned semantics only by the host specified in the domain part of the address.

https://www.rfc-editor.org/rfc/rfc5321

And the portion after doesn't even require a .. So, despite the downvote, this is the correct answer.

For more information, http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/

Community
  • 1
  • 1
dave
  • 62,300
  • 5
  • 72
  • 93
  • naahh, too shallow! there are tons of other things to validate in an email adress. – Tolga Evcimen Sep 10 '14 at 05:27
  • @TolgaEvcimen http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/ – dave Sep 10 '14 at 05:35
  • I read the article, and take a look at comments, and I still think this is not the way to go with the emails. There certainly are some rules with RFC, I'm not saying above regexes are validating it, but at least they are not letting everything in. – Tolga Evcimen Sep 10 '14 at 05:48
  • And if you want a usable email through the internet why would you pick an absurd one, just think about programming languages they allow us to use variable names almost as much as our memories, but do we use that long variable names just because we can? – Tolga Evcimen Sep 10 '14 at 05:50
  • The point is, you'll miss something valid, and if someone wants to lie about their email address, they'll use qwiufaisjdbvaadsjghb@gmail.com and it will pass your filter. But if you get tech-savvy user that tries to use john_doe+yoursite.com@gmail.com, and you forgot to allow the `+` so he could set up filters, you messed up and it didn't even accomplish something. Or you just let them put in whatever, send them an email, and make them click confirm. One way is effective, the other just annoys people when you mess up, and doesn't stop people from using fake emails. – dave Sep 10 '14 at 05:55
  • You are right at some point. But do people really use that kind of email adresses? That's where I'm standing in this conversation. – Tolga Evcimen Sep 10 '14 at 06:09