0

I am trying to add an email validation to one of my forms in a view:

function validateForm(){
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }
}

But I can write the letter @ since it's reserved to C# expressions.

jabaldonedo
  • 25,822
  • 8
  • 77
  • 77
Saar peer
  • 817
  • 6
  • 21
  • It's not really related to your question, but I would suggest you to consider using a regular expression to validate the email address instead. – René Jun 06 '13 at 09:09
  • @Gunder no, you don't validate an email address with a regex. – CodeCaster Jun 06 '13 at 09:41
  • @Gunder http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – CodeCaster Jun 06 '13 at 15:45
  • @CodeCaster Wouldn't you agree that the problem is not in using Regular Expressions (As a technology), but with the regexes people use to catch all invalid emailadresses, which is not practically feasible? There's nothing wrong with using regex'es as input validation in general and even for email adresses, but for email addresses, it's true that you should be conscious about not having a too strict regex, as you'll probably get false positives and anger users. However, my point was that the OP could rewrite his existing validation logic as a regular expression. Would that be a bad thing to do? – René Jun 06 '13 at 16:07
  • @Gunder the core problem is: there is no usable regex for email addresses (apart from a few blurs of characters a few KB in size each). Besides that, validating an email address _by text_ is useless: if you want to validate an email address, send an email to it. Apart from that: yes, OP does not have to do `IndexOf()` magic, the same logic _can_ be written as a regex. – CodeCaster Jun 06 '13 at 16:15
  • 1
    @CodeCaster I completely agree with you. - I probably should have been more clear in my initial comment what I meant. I can see now that it could look like I suggested the OP to look for a 'proper' email regex, however that was not my intention. – René Jun 06 '13 at 16:22

2 Answers2

2

Escape it with at sign before it

@@

Nick
  • 4,192
  • 1
  • 19
  • 30
1

Try this,

function validateForm() {
    var x = document.forms["myForm"]["email"].value;
    var atpos = x.indexOf("@@");//use Escape 
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
}
Satpal
  • 132,252
  • 13
  • 159
  • 168