简体   繁体   中英

Javascript email validation failing on a valid email address?

I seem to be unable to get a basic javascript email validation function to work correctly. It keeps returning that the email address is invalid even when using a real email address.

Could someone please point me in the right direction as i couldn't find the problem on any other similar SO posts. I don't think it's the function itself, but perhaps how i am calling it? I have posted the code below.

 // 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(/^((([az]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\ -\퟿\豈-\﷏\ﷰ-\￯])+(\\.([az]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\ -\퟿\豈-\﷏\ﷰ-\￯])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\ -\퟿\豈-\﷏\ﷰ-\￯])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\ -\퟿\豈-\﷏\ﷰ-\￯]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([az]|\\d|[\ -\퟿\豈-\﷏\ﷰ-\￯])|(([az]|\\d|[\ -\퟿\豈-\﷏\ﷰ-\￯])([az]|\\d|-|\\.|_|~|[\ -\퟿\豈-\﷏\ﷰ-\￯])*([az]|\\d|[\ -\퟿\豈-\﷏\ﷰ-\￯])))\\.)+(([az]|[\ -\퟿\豈-\﷏\ﷰ-\￯])|(([az]|[\ -\퟿\豈-\﷏\ﷰ-\￯])([az]|\\d|-|\\.|_|~|[\ -\퟿\豈-\﷏\ﷰ-\￯])*([az]|[\ -\퟿\豈-\﷏\ﷰ-\￯])))\\.?$/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> 

You should do some basic debugging. Look at the contents of the variables you are testing.

var email = document.getElementById("contact_email");

The value of email is the input element , not the text entered into it. For that you need to read its .value property.

Solution is to add ".value"

var email = document.getElementById("contact_email").value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM