Roy Posted June 11, 2012 Share Posted June 11, 2012 I've been racking my brain over how to achieve this, but I'm stumped. Here's the code I use in the relevant contact.js: function process() { 'use strict'; //set initial check for validation to true because there are no errors yet var okay = true; //reference to email and comments elements var email = document.getElementById('email'); var comments = document.getElementById('comments'); //validate email if (!email || !email.value || (email.value.length < 6) || (email.value.indexOf('@') == -1)) { okay = false; alert('Please enter a valid email address'); }//end if //validate comments if (!comments || !comments.value || (comments.value.indexOf('<') != -1)) { okay = false; alert('Please enter your comments, without any HTML!'); }//end if return okay; }//end process() function //event listener function init() { 'use strict'; //call process upon submission of form document.getElementById('theForm').onsubmit = process; }//end init function() window.onload = init; Link to comment Share on other sites More sharing options...
Larry Posted June 11, 2012 Share Posted June 11, 2012 Sure thing. What you would do to confirm that there's just one @ is to confirm that the indexOf('@') equals the lastIndexOf('@'), assuming that neither equals -1. If the first occurrence of @ in a string is indexed at the same spot as the last occurrence, then there's only one. Link to comment Share on other sites More sharing options...
Roy Posted June 12, 2012 Author Share Posted June 12, 2012 Thank you! Link to comment Share on other sites More sharing options...
markifornia Posted August 8, 2012 Share Posted August 8, 2012 Roy did you get this to work? I may have over complicated the logic or have taken an unnecessary route in my script in what is being pursued here. See my modification to the script below: // Get a reference to form elements. var email = document.getElementById('email'); var comments = document.getElementById('comments'); // Validate the email address: if (!email || !email.value || (email.value.length > 6) || (email.value.indexOf('@') == -1) || (email.value.lastIndexOf('@') == -1)) { // Checks to see that the first instance or last instance is -1 if ((email.value.indexOf('@') != -1) || (email.value.indexOf('@') != -1)) { // Then check if they are equal to each other. if (email.value.indexOf('@') == email.value.lastIndexOf('@')) { okay = false; alert('Two of instances of @ found, please enter a valide email address!'); } } okay = false; alert('Please enter a valid email address!); } Link to comment Share on other sites More sharing options...
Larry Posted August 10, 2012 Share Posted August 10, 2012 You don't need this code: if ((email.value.indexOf('@') != -1) || (email.value.indexOf('@') != -1)) { Because it's in the previous conditional. Link to comment Share on other sites More sharing options...
Recommended Posts