Skip to content

Programming the browser with Javascript

Input validation

Run the application, go to the Courses page and hit on the submit button (without adding any information for the course name/url); what will happen?

As you can see in the image above, a course is added to the list of courses that has no name (and no url). We probably should not allow this!

Recall

Recall we have designed our database schema so that it will not accept a Course with no value (null) for its name. This policy can be extended to a course with empty string as name.

We could check the HTTP Request parameters on the server-side and deal with bad (invalid) input. A more common practice, however, is to validate the input on the client-side. For that, we need to write JavaScript code!

JavaScript

JavaScript is a programming language designed to be run inside a web browser. There are several different versions of JavaScript that are supported by different browsers, but there are certain standard versions that are supported by most. In this class, we will not teach you about JavaScript (although it is very likely that you end up using it-at small or large-for your project).

Tip

I highly recommend the Mozilla MDN Web docs on JavaScript; there are tutorials in there for absolute beginners to advanced users, as well as pointers to other references, tools and resources. JavaScript started at Netscape, the mother company of Mozilla.

Let's do some client-side input validation! Follow these steps:

  • Create the following folder src/main/resources/public/js
  • Create the file validate.js inside the js folder.
  • Update base.hbs and add the following line after the <title> tag:
1
<script src="/js/validate.js"></script>
  • Update courses.hbs and add an id attribute to the input element for course name:
1
<input type="text" placeholder="course name" name="coursename" id="courseName"/>
  • We will use the id attribute to access the value of the input element inside JavaScript code; let's open validate.js and add the following to it:
1
2
3
4
5
6
7
8
9
function validateCourse() {
    var name = document.getElementById("courseName");
    if (name.value.length < 1) {
        alert("Course name cannot be empty!");
        return false;
    } else {
        return true;
    }
}
  • Finally, update courses.hbs and add an event listener to the form element so that upon submission of the form, the validateCourse function is invoked and the form is submitted if and only if that function returned true:
1
<form action="/courses" method="post" onsubmit="return validateCourse();">

Now run the application again, and try to add a course without giving it a name; you must get the following: