0

I am currently having problems with displaying different span error messages for some of the same input texboxes based on if the user doesn't follow my validation rules. I really could use some suggestions of how I can make some of my if statements better to enforce my rules that I have setup. I am okay with how my if statement is validating the username and how if statement is validating the password, but I have been struggling to try to figure what is the best method for validating my repeatemail textbox and emailaddress textbox. Can someone help me? Thanks in advance! Here is my HTML, CSS, and JavaScript/JQuery code

 $('#button2').on('click', function () {
   var NewUsernameError = document.getElementById("New_Username_error"); 
   var NewPasswordError = document.getElementById("New_Password_error"); 
    var NewEmailAddressError = document.getElementById("New_Email_error"); 
  //  var NewRepeatEmailAddressError=document.getElementById("NewReenter_Email_error"); 
   
 // How can I get my span id's to display one of two different error //messages based on my rules below? Right now it will only display first error //messages. Do I need to create two different span ids (except for the password // texbox) for each input textbox or is one span id fine how I currently have //it? Shouldn't I be able to display either message just using one span id?
 

 
 
  if($(".newUsername").val().length < 6)
  { 
       NewUsernameError.innerHTML= "The username must be at least 6 characters"; 
       // NewUsernameError.innerHTML= "There is an already existing account with username"; 
      
   }else
   { 
         NewUsernameError2.innerHTML = '';
   } 
   
    if($(".newPassword").val().length < 6) { 
    { 
       NewPasswordError.innerHTML= "The password must be at least 6 characters"; 
       
   }else{ 
     
       NewPasswordError.innerHTML = '';
    } 
  
    if($(".newEmail")== ""  && $(".newEmail") != /^[a-zA-Z0-9]@[a-zA-Z])+.[a-z])
   { 
      
      NewEmailAddressError.innerHTML= "The email must not be left empty.";  
      NewEmailAddressError.innerHTML= "The email must contain @ symbol  in it.";  

  }else{ 

    NewEmailAddressError.innerHTML= '';  
     
    }
    
 
   if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){ 

     NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered."; 
     NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank."; 
  }else{ 

    NewRepeatEmailAddressError.innerHTML= '';  
     
    } 

.

User445555
  • 66
  • 1
  • 10

2 Answers2

1

Lots of problems here.

if($(".newEmail")== ""  && $(".newEmail") != /^[a-zA-Z0-9]@[a-zA-Z])+.[a-z])

That tries to compare the <input> element instead of its contents.

if($(".repeatEmail").value != $(".newEmail").value && $(".repeatEmail") == ""){ 

That tries to compare undefined instead of the form element's contents. (jQuery doesn't use .value.)

Instead, you want .val():

if($(".newEmail").val() == ""  && $(".newEmail").val() != /^[a-zA-Z0-9]@[a-zA-Z])+.[a-z])
...
if($(".repeatEmail").val() != $(".newEmail").val() && $(".repeatEmail").val() == ""){ 

A secondary problem is where you try to assign two error messages simultaneously:

 NewRepeatEmailAddressError.innerHTML= "This repeat email doesn't equal to the first one entered."; 
 NewRepeatEmailAddressError.innerHTML= "This repeat email must not be blank."; 

In these cases the second .innerHTML is going to immediately overwrite the first one, so the first error message will never be seen. Each of those errors needs to be in its own, separate if {} condition.

Third, this isn't how to do regex comparisons, that regex contains several syntax errors (no trailing slash, mismatched parens), and even if it worked it would disallow many valid email addresses:

$(".newEmail") != /^[a-zA-Z0-9]@[a-zA-Z])+.[a-z])

Better email address validation regexes can be found in e.g. this question, but even those can disallow some valid addresses. Keep things simple and test only for what the error message claims you're testing for, the presence of an @ symbol:

/@/.test($('.newEmail').val())

Putting it all together

Cleaning your original function, converting all the vanilla js into jQuery (there's no real drawback to mixing them other than that it makes the code harder to read, but I figure if you've already got jQuery may as well use it), and rearranging some logic to simplify the code results in this:

var validate=function() {
// clear out the error display ahead of time:
    var newUsernameError = $("#New_Username_error").html('');
    var newPasswordError = $("#New_Password_error").html('');
    var newEmailAddressError = $("#New_Email_error").html('');
    var newRepeatEmailAddressError = $("#Repeat_Email_error").html('');

    // just to make the later conditions easier to read, let's grab all the values into vars:
    var newUsername = $('.newUsername').val();
    var newPassword = $('.newPassword').val();
    var newEmail = $('.newEmail').val();
    var repeatEmail = $('.repeatEmail').val();

    // presumably you'll want to prevent form submit if there are errors, so let's track that:
    var errorsFound = false; 

    if (newUsername === "") {
      errorsFound = true;
      newUsernameError.html("The username must not be empty.");
    } else if (newUsername.length < 6) {
      errorsFound = true;
      newUsernameError.html("The username must be at least 6 characters.");
    }

    if (newPassword.length < 6) {
      errorsFound = true;
      newPasswordError.html("The password must be at least 6 characters.");
    }

    if (newEmail === "") {
      errorsFound = true;
      newEmailAddressError.html("The email must not be left empty.");
    } else if (!/@/.test(newEmail)) {
      errorsFound = true;
      newEmailAddressError.html("The email must contain an @ symbol.");
    }

    if (repeatEmail !== newEmail) {
      errorsFound = true;
      newRepeatEmailAddressError.html("This repeat email doesn't equal to the first one entered.");
    }
    // No need to test for repeatEmail being empty, since that's already covered by the newEmail case above.

    // OK, all conditions checked, now:
    if (errorsFound) {
      // prevent form submit.  (If this is called in an onsubmit handler, just return false.)
    } else {
      // allow form submit.
    }
    console.log("Errors found: ", errorsFound);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
Username: <input class="newUsername">
<div id="New_Username_error"></div>
Password: <input class="newPassword">
<div id="New_Password_error"></div>
newEmail: <input class="newEmail">
<div id="New_Email_error"></div>
repeatEmail: <input class="repeatEmail">
<div id="Repeat_Email_error"></div>
</form>
<button onclick="validate()">Validate</button>
Community
  • 1
  • 1
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • I thought so. Thank you! – User445555 May 09 '17 at 13:23
  • Do I have to create two different span ids or should I just stick with one? One span id for the first error and another span after that, for the second error message – User445555 May 09 '17 at 13:25
  • No -- then both error messages would appear, even if only one of them should have (since you were testing both conditions in the same if clause.) I expanded the answer above to show all your possible error conditions. – Daniel Beck May 09 '17 at 13:40
  • Thanks @Daniel Beck and thanks to all who helped me solve my problem. – User445555 May 09 '17 at 14:13
  • @DanielBeck, Please do explain how the values will be taken if I am taking values by class and not by id? What if I have multiple inputs with same class, in this case wouldn't it be bad to retrive values by class name as they simply pull the first val from the array? – Sagar May 09 '17 at 14:18
  • Not entirely sure I understand what you're asking, but the above code already retrieves data using class selectors: all jQuery selectors return an array of all matched elements, not just the first one (and many jQuery chained functions will act on all elements of that array). If more than one DOM element matches a given selector, you might need to iterate through the returned array to check each one's value, depending on what you're trying to do. Do you have an example of what you're trying to accomplish, so I can demonstrate? – Daniel Beck May 09 '17 at 14:33
  • Oh. I didn't note the username, I thought that was the OP asking, @Sagar. As you probably know, `$('.foo')` returns all `.foo` elements as an array. `$('.foo').val()` will return the first matched element's value, which is what's needed for this particular question. If there were multiple elements with the same classname that needed to be checked separately, you'd likely use `$('.foo').each()` to iterate through each one. – Daniel Beck May 09 '17 at 14:49
  • @DanielBeck I just tried to implement $('.foo').val() with multiple elements and what I found out was that it returns the first element's value. What I had tried to do in my previous code was to point out those fine flaws which I had done with all comments and stuff. However as I am a fresher myself, I tend to give a *hacker's* answer and thus my answer got flawed. :) However I do hope that you point out those minor details in this answer. :) – Sagar May 09 '17 at 15:45
  • @Daniel Beck I tested the repeat email texbox and that functionality does not work. !== should work because if repeat email does not equal to the first email entered, it should display the span error message, but it doesn't. I tried the != operator too but that doesn't work. – User445555 May 09 '17 at 17:52
  • @User445555 I have updated the answer as a code snippet so you can try it out -- I'm not sure what went wrong for you but the 'repeat email' validation does appear to be working correctly. – Daniel Beck May 09 '17 at 18:54
0

Keep one container for the errors you might expect to get on the input. I would do something like this to avoid all the else and else if's

$('#button2').on('click', function () {

  // VALIDATE USERNAME
  var newUserErrStr = '';
  var newUsernameVal = $(".newUsername").val();

  if(newUsernameVal.length < 6) newUserErrStr += "The username must be at least 6 characters";
  document.getElementById("New_Username_error").innerHTML = newUserErrStr;


  // VALIDATE PASSWORD
  var newPasswordErrStr = '';
  var newPasswordVal = $(".newPassword").val();

  if(newPasswordVal.length < 6) newPasswordErrStr += "The password must be at least 6 characters";
  document.getElementById("New_Password_error").innerHTML = newPasswordErrStr;


  // VALIDATE EMAIL
  var newEmailErrStr = '';
  var newEmailVal = $(".newEmail").val();

  if (newEmailVal === "") newEmailErrStr += "The email must not be left empty<br/>";
  if (newEmailVal !== /^[a-zA-Z0-9]@[a-zA-Z])+.[a-z]/ ) newEmailErrStr += "The email must contain @ symbol in it.";

  document.getElementById("New_Email_error").innerHTML = newEmailErrStr;

});
2famous.TV
  • 460
  • 1
  • 6
  • 23