code icon

CSCI 1720

Intermediate Web

Homework 8 - More Form Validation

  1. On your working drive, create a new folder inside your homework folder and name it hw8_jquery-3
  1. Copy the files and folders in your labs/lab10_jquery-1 folder and paste them into the hw8_jquery3 folder. This will be your starting point

I updated the process.php file, so it isn't quite as boring:      process.php. Save this in your project's root folder, over-writing the original

jq icon jQuery

  1. Open the folder as a project in Brackets (remember, Right-click and 'Open as a Brackets project')
  1. Create a new file in the js folder and save it as validate.js
  1. Add a comment block at the beginning of the file (you can copy the comment block from animation.js, paste it into the new file, and change the information as appropriate)
screen shot
Fig. 1- Comment block

Now, originally, I had the code written to just open up that boring old alert box. But we made a much better looking modal in our jquery-2 lab. So let's reuse that code a little, shall we?

  1. Copy the code from labs/jquery-2/js/validator.js and paste it into homework/hw6/js/validate.js

Hint: you can copy/past the code directly from the code block below.

$(document).ready(function() {
    // when user submits form
    $('#submit').on('click', function() {
        // get form information
        let name    = $('#name').val().trim(),
            email   = $('#email').val().trim();

        //check for empty name value
        if (name == '') {
            displayError('Please enter a name');
            return false;
        // check for empty email value
        if (email == '') {
            displayError('Please enter an email address');
            return false;
        // check for valid email address
        if (isEmail(email) == false) {
            displayError('You entered an invalid email address');
            return false;
/*  Delete this, we won't need it for this assignment. The modal is
    only going to launch if there's an error, which is handled by
    the displayError() function
        // if everything is correct,
        // fade the form out
        // build the modal
        $('#modal').html('You entered valid information');
        $('#modal').append('<button id="ok">OK</button>');
        // display the modal
        // reset the form values
    });     // end of Submit event listener
    // called by the submit event listener to 
    // display an error modal. 'm' is the error
    // message
    function displayError(m) {
        $('#modal').append('<button id="ok">OK</button>');

    // fade the modal out and the form back in
    $(document).on('click', '#ok', function() {

    // use regex to validate the entered email format
    // called by the submit event listener
    function isEmail(email) {
        let id      =  '^([a-zA-Z0-9_\\.\\-\\+])+',
            domain  =  '(([a-zA-Z0-9\\-])+\\.)+',
            tld     =  '([a-zA-Z0-9]{2,10})+$',
            regex   =  new RegExp(id + '\\@' + domain + tld);
// combined: /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,10})+$/
//                  id               @       domain     .          tld
        // if the entered email address doesn't match the pattern
        if (!regex.test(email)) {
            return false;
        } else {            // if it does match
            return true;
});     // end of $(document).ready()

  1. We need to modify this code a bit so it will work with our current form. In index.html, change the form's name value to contactForm, delete the onsubmit='validateForm()' attribute/value, and add an id, id='submit' to the submit button
screen shot
Fig. 2- Adding an ID to Submit
Click image to zoom in
  1. We've got a couple more required fields this time, so modify the variables declaration:
screen shot
Fig. 3- Variables
Click image to zoom in

Notice here that we have to change the selector for the name variable to $('#first_name')

With this form, we'd like to capture all of the errors the user may make, rather than displaying them one at a time with a bunch of successive modals. We also want to add some visual feedback to show the user just where he or she screwed up

  1. Modify the if statement for the name variable as follows
screen shot
Fig. 4- Check for empty name field

highlight() and resetBorder() will be created in a little bit. You can see with errorMessage that we're beginning to build the output for the modal. Each check, if triggered, will add its own bit to the message. Also, if the check is triggered, the flag, isValid will be set. We'll use that later to determine whether the form should be submitted

The else statement handles situations where a user might fix one error, but fail to fix others. The corrected field's display will revert to normal

  1. We need to repeat this check for each of the required fields. Ctrl+d or Copy/Paste will be helpful here
screen shot
Fig. 5- Check for email field
screen shot
Fig. 6- Check for state field
screen shot
Fig. 7- Check for occupation field

So we can see with the last four screen shots, the script will check each field to see that everything's kosher. When an error is encountered, the error message is built. That way, when it's displayed, the user will be advised of all of the detected errors at once

  1. Now that we've checked that all of the required fields have data, we have to make sure that the email address is valid. We can use a lot of the code we've already written, with a little revision:
screen shot
Fig. 8- Checking the email address's validity
Click image to zoom in
  1. That's it for the event handler
screen shot
Fig. 9- Closing out the event handler

It took me the longest time, when I was learning JavaScript and jQuery, to get used to the }); notation. If you stop and think about it, it makes perfect sense, given how the anonymous function is nested within the code. Anyway, if you set up the parantheses/brackets first, then add the code, things will usually work out ok

  1. So now we need to set up the 'helper functions' that are called by the event listener
screen shot
Fig. 10- Functions

These two functions toggle the border of the offending text fields - red if they're not filled in; black if they're ok. This provides visual feedback, showing the user which field(s) is/are in error when the field is submitted

  1. Modify the displayError() function and the 'ok' event handler from the jquery-2 lab
screen shot
Fig. 11- Functions for the modal

Notice here that we've removed the form fadeout() method and changed modal to modal-inner. This way, the modal will take up the whole display, while the error message will be displayed in the modal-inner element

Also, we've removed the form fadeIn() method. Ultimately, this time, the modal display will overlay the display, instead of fading the form out and in

Note to self: We have to modify the project's CSS before we're done...

  1. Here we can see one of the benefits of reusing code: We've already written the code for validating an email address. We've tested it and verified that the logic is working correctly. So, there's no need to change it from the lab
screen shot
Fig. 12- Already done!
Click image to zoom in
  1. A final tweak: when the user does submit the form successfully, the receiving script generates an acknowlegement with a 'Back' arrow that will return to the form. At that point, the form's fields should be reset. So add the following code BEFORE the Submit event handler code
screen shot
Fig. 13- Already done!

This may seem a little counterintuitive. Why are we resetting the form before it's submitted? The answer is that the form will be initialized every time the document loads. The first time, it's already initialized, so it isn't noticeable. Subsequent times, (i.e., when the user returns to it after successful submission), it will initialize again, resetting the form values

Updating the CSS

  1. We have to make a couple of additions/modifications to our stylesheet. Once again, copy the following code from the jquery-2 lab and paste it into your current project's style.css file:
#modal {
    display: none;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    height: 150px;
    padding: 20px;
    background: #444;
    color: #ddd;
    text-align: center;
    font-size: 2rem;
    z-index: 1;

#modal #ok {
    position: absolute;
    bottom: 15px;
    left: 50%;
    transform: translateX(-50%);
    width: 100px;
    height: 40px;
    border-radius: 25px;
    border-width: 0;
    background: #ddd;
    color: #444;
    font-size: 1.4rem;
    cursor: pointer;

#modal #ok:hover {
    transition: .5s;
    opacity: 0.6;
    cursor: pointer;
  1. Modify the code as follows:
screen shot
Fig. 14- Splitting the modal

While we're reusing the code to a large degree, pay close attention here. We also have to modify a few values and add a few properties/values to make it work.

Since #modal and #modal-inner share some properties and values, I'd duplicate the original #modal id, rename the second to #modal-inner, and make the above-listed changes to each

Some of the values for #modal-inner, by the way, were determined by again using the Developer Tools to tweak the appearance, then copying/pasting the code back in to the source document. I thought about having y'all do this, but the assignment's getting a little long already. Feel free, though, to experiment with the values to make the element display more to your liking

  1. The modal element isn't currently part of the index.html file. Add the following above the script calls:
screen shot
Fig. 15- Adding the modal to the HTML

I still think this is super cool: the element starts the day empty (we probably don't even need the display: none; property in the CSS). It only is populated and displayed in response to a user error

Uploading / Testing

Now we have the jQuery and CSS done (sort of), what have we (I) forgotten? Oh yeah! Add a link to index.html that includes validate.js

screen shot
Fig. 16- Adding the modal to the HTML
  1. Save your work and upload everything to the server with FileZilla (it has to be run from the server for the processing file to work) into a new folder, /homework/hw8_jquery3
  1. Navigate to the page in a web browser
  1. Test the code
    • Fill out the form correctly and click 'Submit'
    • Return to the form and refresh the page. Then click 'Submit' to check that the jQ code correctly captures the empty field(s) and highlights the missing ones
    • Check the email validation by entering an incorrectly formatted email address
    • Try different combinations or 'errors' to make sure the script catches any and all empty fields

One potential scenario is that the user messes up two or more times. As the user corrects each omission and tries to submit the form, the error message will display differently and the border for the corrected field will be reset

  1. If the code is correct, script should run and display the feedback form

A few styling tweaks

Of course, that's good as far as it goes, but let's style the form a little better. Along the way, we'll learn a new way to select HTML elements in CSS (I think, thinking about it more, we may already have discussed this. But either way...)

  1. Let's take a look at what we've got so far
screen shot
Fig. 17- Current 'state of the form'

It's looking pretty good. But we can make some subtle changes that will make it look more contemporary and professional

  1. Return to style.css in Brackets

Now, there's a way we can select HTML for our CSS using an elements or elements' values. This is super cool, particularly when styling forms, which have a bunch of <input> elements of different types. We can single out a specific type for styling

  1. Add the following
screen shot
Fig. 17- Selecting by attribute

We could use any attribute here. For example, we could style an anchor element that has a certain href attribute value:

screen shot

would apply those rules only to links to ETSU's website

  1. Add the following rules. This will make the text input fields a little bigger and will add some padding to the input
screen shot
Fig. 18- Styling text input boxes
  1. The labels look ok, but I'd like to reposition them a little bit
screen shot
Fig. 19- Positioning labels

I used the developer tools trick again to get the position the way I wanted it. You might have different ideas - feel free to play around with this. I tested the final product for responsiveness and it worked pretty well

  1. Save your work and upload everything to the server. Test the page's functionality & make sure you didn't break anything. Also check the valildation links to make sure the HTML and CSS don't have any errors
screen shot
Fig. 20- Final product
  1. Make sure to test all possible use-cases once the page is finished to make sure you didn't break anything
  1. Copy/paste the URL for the page into a text file and upload it to D2L

Have a nice day 😊