Validating an email address is an essential step in almost any web or desktop application. Incorrect or malformed emails can cause delivery issues, bounce-backs, or even compromise security. Below you’ll find practical regular expressions and code samples for email validation in multiple programming languages including JavaScript, C#, PHP, and VBScript.
The Regular Expression
A commonly used regex for validating email addresses:
^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$
JavaScript Example
In client-side validation, JavaScript is the first line of defense before submitting a form:
function validateEmail(form) {
// Validating the email field
var re = /^(([^<>()[\]\\.,;:\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 (! form.Email.value.match(re)) {
alert("Invalid email address");
form.Email.focus();
form.Email.select();
return false;
}
return true;
}
C# Example
In C#, the Regex class can be used to validate email addresses server-side:
public static bool isEmail(string inputEmail) {
inputEmail = NulltoString(inputEmail);
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
return re.IsMatch(inputEmail);
}
PHP Example
In PHP, validation can be performed using string functions or built-in filters:
<?php
function Verify_Email_Address($email_address) {
// Assumes that valid email addresses consist of user_name@domain.tld
$at = strpos($email_address, "@");
$dot = strrpos($email_address, ".");
if($at === false || $dot === false || $dot <= $at + 1 || $dot == 0 || $dot == strlen($email_address) - 1)
return false;
$user_name = substr($email_address, 0, $at);
$domain_name = substr($email_address, $at + 1, strlen($email_address));
if(Validate_String($user_name) === false || Validate_String($domain_name) === false)
return false;
return true;
}
?>
VBScript Example
For legacy systems, VBScript can still validate emails:
<script language="vbscript">
function ValidateEmail(sEmail)
set myExpression = new RegExp
myExpression.pattern = "^(\w+\.)*(\w+)@(\w+\.)+([a-zA-Z]{2,4})$"
If myExpression.test(sEmail.value) = True Then
msgbox "Valid Email"
Else
msgbox "Invalid Email"
End If
End Function
</script>
<form name="email">
<input type=text name="txtEmail" maxlength=44 width=40>
<input type=button onclick="ValidateEmail(txtEmail)">
</form>
Conclusion
Validating email addresses prevents invalid input and ensures proper message delivery. Use regular expressions as a quick check, but remember that only sending a confirmation email truly guarantees an address exists. For modern applications, combining regex validation with real-time email verification services is the most reliable approach.