0

I edited an existing validated function (included in a WordPress plugin) to add email validation feature.

function validateForm(form){
    var $ = jQuery;

// The code snippet I added
// **********************************
var emailID = document.getElementsByName('useremail')[0].value;
    atpos = emailID.indexOf("@");
    dotpos = emailID.lastIndexOf(".");

   if (atpos < 1 || ( dotpos - atpos < 2 ))
    {
        alert("Please enter correct email ID")
        return false;
    }

// End of the code added by me

else if(!$('input[name=title]', form).val()){
     alert("Please enter correct Name")
    $('input[name=title]', form).focus();
    return false;
    }
// ...
return true;
}

The html code:

<input type="text" name="useremail" id="useremail" required>

The email validation code was derived from Validate email address in JavaScript?.

I think the part var emailID = document.getElementsByName('useremail')[0].value; is not correct.

I tried also to use var emailID = document.getElementById('useremail'); which also does not work.


Added: var emailID = document.getElementById('useremail'); should work. The problem was that the js file was not properly enqueued in WordPress. Thanks for all comments.

Community
  • 1
  • 1
Peter
  • 692
  • 3
  • 10
  • 24
  • 1
    You think? Do a `console.log(emailID)`, is it what you expect it to be? Also note for the `id` it would be: `document.getElementById('useremail').value`. – Spencer Wieczorek Oct 09 '15 at 01:35
  • `String.match()` or `RegExp.test()`. – StackSlave Oct 09 '15 at 01:37
  • Try using `var email = document.querySelector('#useremail').value` – jusopi Oct 09 '15 at 01:40
  • 2
    why not use regular expression? – Lucius Oct 09 '15 at 01:42
  • he can't even get the value from the input to use in a regexp if I understand his question. But yes, I was wondering why not use the regexp too rather than all the positional checks. – jusopi Oct 09 '15 at 01:44
  • Your `var` declarations are incorrect. You need commas between the individual variables, and just one semicolon at the end of the statement.' – Pointy Oct 09 '15 at 01:44
  • that wouldn't be causing the issue would it? Although he's declaring global vars it should still work no? – jusopi Oct 09 '15 at 01:45

1 Answers1

0

The code works correctly in this fiddle: https://jsfiddle.net/adriel_santos/2rtya7pz/3/

Keep in mind that HTML5 has an input type that holds email:

 <input type="email" name="useremail" id="useremail" required>
Adriel Santos
  • 653
  • 7
  • 15
  • Note that you use `var emailID = $('#useremail').val();` instead of `var emailID = document.getElementsByName('useremail')[0].value;` (I'm assuming by your code that you have loaded the jquery library) – Adriel Santos Oct 09 '15 at 01:50