DEV Community

Cover image for Vue JS Form Validation Using Options API
Raja Tamil
Raja Tamil

Posted on • Updated on

Vue JS Form Validation Using Options API

In this article, I’m going to cover how to validate a simple sign-up form on the client-side in vue.js using Options API.

I also have an article on how to do Form Validation using Vue JS 3 Composition API for Sign-up and login pages, in case if you’re interested in that as well.

As you can see from the final output below, when I press the sign-up button with all the input fields empty, error messages appear above the sign-up form.

When I enter the wrong email address, I get a different validation error, this time saying invalid email.

alt text

Finally, I am going to restrict the length of the password to be at least 8 characters.

In this process, I’ll be showing you how to:

  • Create and bind user object properties to the input fields
  • Attach an event to the form or to a button inside the form
  • Show you different ways of preventing the default form submission behaviour
  • Validate all the input fields
  • Show how to accumulate all the errors in the errors array and show them on the view

I’m very excited to show you them all! It is a lot of cover so let’s get started.

This is a part of a series and I’ve already covered how to design a sign-up form in one of my other articles.

Create User Object

In the SignUp.vue component, add script tags in between the template and style tags.

Then declare the export default object. This is where we’re going to add all of our JavaScript code for this component.

Next, define a data model, which is a function that returns an object.

<script>
  export default {
    data() {
      return {}
    },
</script>
Enter fullscreen mode Exit fullscreen mode

Then, declare a property called user and the value of the user property is going to be a JavaScript object.

In there, I am going to create three properties:

  • Name
  • Email
  • Password
<script>
  export default {
    data() {
      return {
        user: {
          name: "",
          email: "",
          password: "",
        },
      };
    },
</script>
Enter fullscreen mode Exit fullscreen mode

Now that we have the properties we need, let’s go ahead and bind them to the input fields.

Bind User Object To The Input Fields

Go to the name input field at the top and before the self-closing angle bracket, bind the name property from the user object to this name input field using v-model directive.

<!-- FULL NAME -->
<div class="field">
  <div class="ui left icon input big">
    <i class="user icon"></i>
    <input type="text" placeholder="Full Name" v-model="user.name" />
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Note: The .name here must be matched with the name property inside the user object.

Let’s bind the other two in the same way.

<!-- EMAIL -->
<div class="field">
  <div class="ui left icon input big">
    <i class="mail icon"></i>
    <input type="email" placeholder="Email" v-model="user.email" />
  </div>
</div>
<!-- PASSWORD -->
<div class="field">
  <div class="ui left icon input big">
    <i class="lock icon"></i>
    <input type="password" placeholder="Password" v-model="user.password" />
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

It’s important to create a property first inside the data() model before binding it to the view, otherwise, Vue will throw the undefined property error which looks something like this.

alt text

Attach A Click Event To The Sign-Up Button

Next, attach a click event to the sign-up button.

Go to the sign-up button element and before the closing angle bracket in the starting button tag, bind a click event to the button using v-bind:click=””.

Then add the callback function called signUpButtonPressed.

<button class="ui button big red fluid" v-bind:click="signUpButtonPressed">SIGN UP</button>
Enter fullscreen mode Exit fullscreen mode

Actually there is a shortcut for binding a click event to a button. Instead of using v-bind:click, I can simply use @click which will do the exact same thing but looks much cleaner.

<button class="ui button big red fluid" @click="signUpButtonPressed">SIGN UP</button>
Enter fullscreen mode Exit fullscreen mode

Declare The Sign-Up Button Callback Function

In Vue 2 Options API, all of the functions must be declared inside the methods object.

So inside the methods object declare a signUpButtonPressed callback function.

export default {
  data() {
    ...
  },
  methods: {
    signUpButtonPressed() {
      console.log("Sign up button pressed!")
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Let’s run the app to check if the sign-up button works.

Open up the Terminal, go to the project directory and run npm run dev. Then go to the URL on the browser and make sure to go to the /signup route.

Let’s open up the browser console to see if the button press is working.

alt text

Oh wait! Something has happened?

Two things have happened. There is a ? mark added to the URL as well as we cannot see the console log message.

However, when I click the sign-up button a second time, I can see the message in the console as expected.

Form Submit Default Behaviour

But the question is why is it not working the first time?

When I click the sign-up button for the first time, it basically reloads the page and tries to submit the form data via GET request – that’s why we see the question mark (?) in the URL.

This is the default behaviour of a

element when a button inside is pressed.

As you can see, even though I did not add the type=”submit” attribute to the button element, the form can still be submitted.

Also, you can see the console message is actually visible on the browser console for a second and then it quickly disappears as the page gets reloaded.

alt text

There are THREE ways to prevent the default form submission behaviour:

  • Using preventDefault() method on the click event object
  • Adding prevent modifier when attaching a click event to the sign-up button
  • Adding prevent modifier when attaching submit event to the form element. Alternatively, I can use preventDefault() method as well, similar to the click event.

PreventDefault Method On The Event Object

The first option is to call the preventDefault() method on the click event object that is passed into the signUpButtonPressed callback function.

Continue Reading...

Top comments (1)

Collapse
 
roblevintennis profile image
Rob Levin

It's now all about the composition api baby! 💪 💯 😄