Search⌘ K

Challenge Solution: Model Validations

Explore how to implement model validations in plain JavaScript to maintain data integrity. This lesson helps you understand checking constraints on data attributes, such as IDs, titles, and dates, and applying validation functions before setting values in your app's model.

We'll cover the following...

Solution

Let’s take a look at the code for the challenge solution.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta charset="UTF-8"/>
  <title>Plain JS Validation App: Create</title>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="theme-color" content="#ffffff"/>

  <link rel="stylesheet" href="css/normalize.css"/>
  <link rel="stylesheet" href="css/main.css"/>

  <script src="src/v/createMovie.mjs" type="module"></script>
</head>
<body>
<header>
  <div class="wrapper clearfix">
    <div class="title">
      <h1>Create a new movie record</h1>
    </div>
    <nav>
      <ul>
        <li><a href="createMovie.html">C</a></li>
        <li><a href="retrieveAndListAllMovies.html">R</a></li>
        <li><a href="updateMovie.html">U</a></li>
        <li><a href="deleteMovie.html">D</a></li>
      </ul>
    </nav>
  </div>
</header>
<main>
  <div class="wrapper clearfix">
    <form id="Movie">
      <div><label>Movie ID: <input name="movieId" type="text"/></label></div>
      <div><label>Title: <input name="title" type="text"/></label></div>
      <div><label>Release date: <input name="releaseDate" type="date"/></label></div>
      <div>
        <button type="submit" name="commit">Save</button>
      </div>
    </form>
    <a href="index.html">Back to main menu</a>
  </div>
</main>
</body>
</html>
Solution

Explanation

Let’s take a look at what we did in the code.

src/m/Movie.mjs

  • Lines 33–41: The checkMovieId function checks for two violations. The first is if id is a non-integer, and the second is if id is 0 or ...