Step 7: validating posts

Validating new posts.

We learnt how to create new posts. Now we may want to add some validation rules for them. You do not want to get empty posts or very short ones.

We're going to use client side validation to check if either title or body are longer than 4 characters, for example.

What is client side validation?

Also, we want to show some kind of warning when a user tries to create a post that does not pass our super cool validation rule.

Replace:

<form id="post-form">
  <div class="form-group">
    <label for="post-title" class="control-label">Post Title</label>
    <input type="text" class="form-control" id="post-title" placeholder="A new post"/>
  </div>
  <div class="form-group">
    <label for="post-body" class="control-label">Post Content</label>
    <textarea type="text" class="form-control" id="post-body" placeholder="A new Body"></textarea>
  </div>
  <button type="submit" class="btn btn-primary">Post</button>
</form>

with

<form id="post-form">
  <div class="form-group">
    <label for="post-title" class="control-label">Post Title</label>
    <input type="text" class="form-control" id="post-title" placeholder="A new post" minlength="4"/>
  </div>
  <div class="form-group">
    <label for="post-body" class="control-label">Post Content</label>
    <textarea type="text" class="form-control" id="post-body" placeholder="A new Body" minlength="4"></textarea>
  </div>
  <button type="submit" class="btn btn-primary">Post</button>
</form>

What have we done here?

We have added a property minlength to both text inputs. This allows HTML5 form controls to check the length of the text we're inputting and to automatically act at elements class for displaying validation errors.

Last updated