我似乎无法获得基本的javascript电子邮件验证功能才能正常工作。即使使用真实的电子邮件地址,它仍会返回电子邮件地址无效。
有人可以指出我正确的方向,因为我无法在任何其他类似的SO帖子上找到问题。我不认为它是功能本身,但也许我怎么称呼它?我已经发布了以下代码。
// E-mail validation via regular expression - taken from SO solution
// Needs to be accessible for other Forms to use
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
// Validate Contact Form
function validate_contact(evt) {
var error = '';
// Set Veriables
var email = document.getElementById("contact_email");
// Validate Other Fields Here
// - Removed for Example -
// Validate Email Address
if (!isValidEmailAddress(email)) {
error += '- Please enter a valid Email Address.\n';
}
// Show Error Notice
if (error != '') {
error = 'The form has not been completed correctly, please check the following:\n\n' + error;
alert(error);
evt.preventDefault(); // Stop the event
} else {
// Proceed
}
}
// Get reference DOM elements
var contact_form = document.getElementById("contact_form");
// Set up event - Contact Form Validation
contact_form.addEventListener("submit", validate_contact);
// Set up event - Other Form Validation
//other_form.addEventListener("submit", validate_other);

<form id="contact_form" method="post" action="" autocomplete="off">
<input type="text" id="contact_email" name="email" value="">
<input type="submit" id="submit">
</form>
&#13;
答案 0 :(得分:5)
你应该做一些基本的调试。 查看您正在测试的变量的内容。
var email = document.getElementById("contact_email");
email
的值是输入元素,而不是输入的文本。为此,您需要阅读其.value
属性。
解决方案是添加“.value”
var email = document.getElementById("contact_email").value;