我正在尝试验证在文本框中输入的电子邮件地址,我希望当用户使用无效的电子邮件地址留下电子邮件地址字段时显示错误消息“电子邮件地址无效。”
答案 0 :(得分:5)
您可以使用filter_var ()
<?php
$email_address = "me@example.com";
if (filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
// The email address is valid
} else {
// The email address is not valid
}
?>
答案 1 :(得分:3)
您可以查看此link
<?php
$email = "someone@example.com";
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
}
else
{
echo "E-mail is valid";
}
?>
答案 2 :(得分:2)
电子邮件验证
<?php
$email_a = 'joe@example.com';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
}
else
{
echo "This ($email_a) email address is not considered valid.";
}
答案 3 :(得分:0)
来自http://jqueryvalidation.org/email-method
<body>
<form id="myform">
<label for="field">Required, email: </label>
<input class="left" id="field" name="field">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script src="http://jquery.bassistance.de/validate/additional-methods.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
field: {
required: true,
email: true
}
}
});
</script>
</body>
答案 4 :(得分:0)
以下是有效电子邮件地址的快速有效方法
<?php
$email = "abc123@lolhaha"; // Invalid email address
//$email = \"somebody@somesite.com\"; // Valid email address
// Set up regular expression strings to evaluate the value of email variable against
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
// Run the preg_match() function on regex against the email address
if (preg_match($regex, $email)) {
echo $email . " is a valid email. We can accept it.";
} else {
echo $email . " is an invalid email. Please try again.";
}
?>
答案 5 :(得分:0)
你可以使用,
if (filter_var($email_address, FILTER_VALIDATE_EMAIL))
{
#valid email
}
else
{
#inavalid email
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0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';
if (preg_match($pattern, $$email_address) === 1) {
// emailaddress is valid
}
或使用jQuery
var email = $('#email').val();
var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);