Jump to content
Larry Ullman's Book Forums

Chapter 5 Pursue: Check For One @ In Email


Recommended Posts

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 post
Share on other sites

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 post
Share on other sites
  • 1 month later...

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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...