0

I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything... Thanks for your help!!

My HTML:

<form name="user_details" method="post" onsubmit="return checkform()">
    <table id="form_table">
        <tr>
            <td class="form_cell"><label for="first_name">First Name:</label></td> 
            <td class="form_cell"><input type="text" id="first_name">*</td>
            <td id="error_first_name">The first name field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="surname">Surname:</label></td>
            <td class="form_cell"><input type="text" id="surname">*</td>
            <td id="error_surname">The surname field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="address">Address:</label></td>
            <td class="form_cell"><input type="text" id="address">*</td>
            <td id="error_address">The address field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="city">City:</label></td>
            <td class="form_cell"><input type="text" id="city">*</td>
            <td id="error_city">The city field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="post_code">Post Code:</label></td>
            <td class="form_cell"><input type="text" id="post_code">*</td>
            <td id="error_post_code">The post code field needs to contain a number.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="email">Email:</label></td>
            <td class="form_cell"><input type="email" id="email">*</td>
            <td id="error_email">The email field needs to contain an email address.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
            <td class="form_cell"><input type="text" id="phone_number"></td>
        </tr>
    </table>
        <input type="submit"><input type=reset>
    </form>

My JavaScript:

function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
} 

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
} 

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
} 

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
} 

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
} 


else {
    return ok;
}

}

My CSS:

#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}
Marie
  • 55
  • 1
  • 6
  • don't put return in else condition ! It will return all of your condition as one result so put outside if else condition `return ok;` remove `else {}` – Jack jdeoel Jun 06 '17 at 08:57

4 Answers4

1

Apply the return ok in end of the function also

function checkform() {
  var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

  if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
  } else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
  } else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
  } else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
  } else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
  } else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
  } else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
  } else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
  } else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
  } else {
    return ok;
  }
   return ok;
}
#error_first_name {
  display: none;
}

#error_surname {
  display: none;
}

#error_address {
  display: none;
}

#error_city {
  display: none;
}

#error_post_code {
  display: none;
}

#error_email {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return checkform()">
  <table id="form_table">
    <tr>
      <td class="form_cell"><label for="first_name">First Name:</label></td>
      <td class="form_cell"><input type="text" id="first_name">*</td>
      <td id="error_first_name">The first name field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="surname">Surname:</label></td>
      <td class="form_cell"><input type="text" id="surname">*</td>
      <td id="error_surname">The surname field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="address">Address:</label></td>
      <td class="form_cell"><input type="text" id="address">*</td>
      <td id="error_address">The address field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="city">City:</label></td>
      <td class="form_cell"><input type="text" id="city">*</td>
      <td id="error_city">The city field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="post_code">Post Code:</label></td>
      <td class="form_cell"><input type="text" id="post_code">*</td>
      <td id="error_post_code">The post code field needs to contain a number.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="email">Email:</label></td>
      <td class="form_cell"><input type="email" id="email">*</td>
      <td id="error_email">The email field needs to contain an email address.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
      <td class="form_cell"><input type="text" id="phone_number"></td>
    </tr>
  </table>
  <input type="submit"><input type=reset>
</form>
prasanth
  • 22,145
  • 4
  • 29
  • 53
1

I want to highlight some points based on your code

  1. The errors is because you didn't include a jquery version in your code.
  2. If you are using jquery then short your code using it.
  3. Don't repeat same property to each id in CSS use a class instead.
  4. Check empty and regex in single condition using ||

function checkform() {
  var ok = true,
    first_name = $.trim($("#first_name").val()),
    surname = $.trim($("#surname").val()),
    address = $.trim($("#first_name").val()),
    city = $.trim($("#city").val()),
    post_code = $.trim($("#post_code").val()),
    email = $.trim($("#email").val());
  $('input.bdred').removeClass('bdred');
  $('.errors').hide();
  if (!first_name || !/^[A-Za-z]+$/.test(first_name)) {
    $("#first_name").addClass('bdred');
    $("#error_first_name").show();
    ok = false;
  } else if (!surname || !/^[A-Za-z]+$/.test(surname)) {
    $("#surname").addClass('bdred');
    $("#error_surname").show();
    ok = false;
  } else if (!address || !/^[A-Za-z]+$/.test(address)) {
    $("#address").addClass('bdred');
    $("#error_address").show();
    ok = false;
  } else if (!city || !/^[A-Za-z][0-9]+$/.test(city)) {
    $("#city").addClass('bdred');
    $("#error_city").show();
    ok = false;
  } else if (!post_code || !/^[0-9]+$/.test(post_code)) {
    $("#post_code").addClass('bdred');
    $("#error_post_code").show();
    ok = false;
  } else if (!email || !/\S+@\S+/.test(email)) {
    $("#email").addClass('bdred');
    $("#error_email").show();
    ok = false;
  }
  return ok;
}
.errors {
  display: none;
}

.bdred {
  border-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="user_details" method="post" onsubmit="return  checkform();">
  <table id="form_table">
    <tr>
      <td class="form_cell"><label for="first_name">First Name:</label></td>
      <td class="form_cell"><input type="text" id="first_name">*</td>
      <td id="error_first_name" class="errors">The first name field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="surname">Surname:</label></td>
      <td class="form_cell"><input type="text" id="surname">*</td>
      <td id="error_surname" class="errors">The surname field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="address">Address:</label></td>
      <td class="form_cell"><input type="text" id="address">*</td>
      <td id="error_address" class="errors">The address field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="city">City:</label></td>
      <td class="form_cell"><input type="text" id="city">*</td>
      <td id="error_city" class="errors">The city field needs to contain at least one character.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="post_code">Post Code:</label></td>
      <td class="form_cell"><input type="text" id="post_code">*</td>
      <td id="error_post_code" class="errors">The post code field needs to contain a number.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="email">Email:</label></td>
      <td class="form_cell"><input type="email" id="email">*</td>
      <td id="error_email" class="errors">The email field needs to contain an email address.</td>
    </tr>
    <tr>
      <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
      <td class="form_cell"><input type="text" id="phone_number"></td>
    </tr>
  </table>
  <input type="submit"><input type=reset>
</form>
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

If you used jquery ,you can shorten your code with making array for same pattern group and using .each

function checkform() {
    var ok = true;
    var character = [["first_name","surname","address"],["/^[A-Za-z]+$/"]];
    var city = [["city"],["/^[A-Za-z][0-9]+$/"]];
    var post = [["post_code"],["/^[0-9]+$/"]];
    var email = [["email"],["/\S+@\S+/"]];
    $("form[name='user_details'] input").each(function(){
        if($.inArray(this.id,character[0]) >= 0 ) {
            ok = showError(this,character[1]);      
        } else if(this.id == city[0]) {
            ok = showError(this,city[1]);
        } else if(this.id == post[0]) {
            ok = showError(this,post[1]);
        } else if(this.id == email[0]) {
            ok = showError(this,email[1]);
        }
    });
    return ok;
}
function showError(t,p) {
    if(t.value == "" || !p.test(t.value)){
        $(t).css("borderColor","red");
        $("#error_"+t.id).show();
        return false;
    }
    return true;
}
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52
0

You have several issues in your code and you can improve it in many factors, see below.

  1. You don't close the function checkform() properly, you're missing a closing bracket.
  2. You want to return ok from the function no matter what, so you should omit the else block, for example:

    function checkform() {
        var ok = true,
        [ omitted for brevity ]
        else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
            document.getElementById("first_name").style.borderColor = "red";
            ok = false;
        } 
    
        return ok;
    }
    
  3. You probably want to check all the errors at form submit. Currently what your code does is look for errors in each field and when it encounters one it will display the error message and stop looking for other errors. To change it you should give up else if in favor of just series of if, like so:

    function checkform() {
        var ok = true,
        [ omitted for brevity ]
    
        if (document.getElementById("first_name").value == "") {
            document.getElementById("first_name").style.borderColor = "red";
            $("#error_first_name").show();
            ok = false;
        } // See here - it will check each field no matter what
        if (document.getElementById("surname").value == "") {
            document.getElementById("surname").style.borderColor = "red";
            $("#error_surname").show();
            ok = false;
        }
        return ok;
    }
    
  4. You are not resetting field style if the error is gone. For example - user tries to submit an empty form, so all fields signal an error. Then the user fills just first name and submits, but the error is still shown, because you never reset it. You could add an else to each check and act accordingly.

  5. You should use === for string comparison (see this answer)
  6. I see you are using jQuery, you should not mix "bare" js (like document.getElementById with jQuery code, because it makes the code messy. With jQuery you can get value of a field like so: $('<css selector here>').val(), for example $('#first_name').val() and you can change styles, by doing $('<css selector>').css('<property', '<value>')
  7. You should not mix presentation and code (like setting styles) instead add and remove a css class and style it in your stylesheet. You can add class with jQuery like so: $('<css selector').addClass('<you class name') and remove it analogically $('<css selector').removeClass('<you class name')
  8. You should attach your event handlers (like onsubmit) in your script file, so you don't clutter your HTML with event handlers and JS with a lot of functions called only from HTML. This improves readability of your code. You can attach your event handler in jQuery like so:

    $(function() { // This wait's for document.ready.
        // It's required to attach event in script
        // because scripts are ran before browser parses HTML
        $('#formId').submit(function() {
            return false; // This gets called on form submit
        });
    });
    

I've created a plunker that demonstrates all of my points

For more information you should see jQuery website and other questions at stackoverflow.

Enbyted
  • 68
  • 8
  • Thank you so much Enbyted!!! By the end of yesterday nothing made sense anymore but thanks to your detailed explanation I now know what I am doing :) – Marie Jun 07 '17 at 07:46