im trying to validate an email address with this regular expression .*@.*\..*
im just wondering how i can change this to also check if the string is more than one character?
Asked
Active
Viewed 632 times
0

phil crowe
- 633
- 1
- 5
- 4
-
1Well, if the string must contain `@` and `.`, it already has 2 characters. – Kobi May 18 '11 at 11:05
-
ye but when i use this expression in the asp regular expression validator it doesnt show the message when the field is blank? – phil crowe May 18 '11 at 12:48
5 Answers
3
Use the +
specifier instead of *
to make sure that there is at least one character:
.+@.+\..+
This will actually ensure that there is at least five characters, as you can't have a public email address that makes sense with less than that. You could make a more elaborate check (for example based on the minimum length of domain names and the allowed characters), but this at least covers the most basic requirements.

Guffa
- 687,336
- 108
- 737
- 1,005
-
i still dont get an error message when i use this in the asp.net regular expression validator control. the page seems to be invalid because it wont post but there is no message next to the email field if i leave it blank. there is if i write something like 'test', which doesnt match the expression. – phil crowe May 18 '11 at 12:51
-
1@phil crowe: The RegularExpressionValidator only validates data if there is any. You need a RequiredFieldValidator also to make the validation fail for blank values. – Guffa May 18 '11 at 13:19
-
@phil - this is exactly why you should always explain exactly what you're trying to do, and what doesn't work. There regex isn't the issue at all, and another regex will not solve your problem. – Kobi May 18 '11 at 13:28
-
i was trying to avoid the requiredfield validator if possible, so bascially you cant check this through a regualr expression? @kobi i did have more of an explanation but stack overflow kept saying i could post my question with no explanation, someone suggested dumbing it down. – phil crowe May 18 '11 at 13:45
-
@phil crowe: That is correct, the RegularExpressionValidator can not be used to make a field required. – Guffa May 18 '11 at 13:55
1
You don't need to do length checks with Regex, just use the string length option:
string Email = "tom@tom.com";
// Regex checks here
if(Email.Length > 1){
}
Also I would recommend not validating email addresses. It's insanely complicated, see this question for more information:

Community
- 1
- 1

Tom Gullen
- 61,249
- 84
- 283
- 456
0
Use below for email validation
function chkEmail(theField,msg)
{
var a=theField.value;
var reg_mail=(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+(\.[A-Za-z0-9]{2,3})(\.[A-Za-z0-9]{2,3})?$/);
if((a.search(reg_mail)==-1))
{
alert(msg);
theField.focus();
return false;
}
return true;
}
Use below for length
if(document.getElementById('id').value.length > 1)
{
}

Saurabh
- 5,661
- 2
- 26
- 32