Validating inputs with pristine Vue.js

I am working on creating a vue.js based form validation system that validates input on-the-fly without the need for page refresh.

Currently, I have implemented the following code for email field validation:

<div class="container" id="forms" >
<label for="inputEmail" class="sr-only"></label>
<input type="email" id="inputEmail" class="form-control" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb8a5bcb0adb1b89db9b2b0b8b3f3beb2b0">[email protected]</a>" required v-model='email'>
<div class="error" v-show="email &amp;&amp; !isEmailValid"><span style="color:red;">Input Correct e-mail </span></div></div>

new Vue({
el: '#forms',
data: { email: ''},
computed: {isEmailValid: function isEmailValid() {
        return (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(this.email)
        ); } } });

However, when I try to apply similar validation patterns to other form inputs, it seems to break. It either displays error messages from the beginning or doesn't show any errors regardless of the input provided.

You can access the fiddle with this link.

I suspect there might be a mistake in the script section where I am trying to make everything work. There could be an issue with declaration or syntax that I am struggling to pinpoint. I've tried various solutions, but nothing seems to fix the problem. Can anyone please assist me?

Answer №1

It is imperative to understand the limitations when it comes to defining properties in Vue components. You are allowed only one data and one computed property.

A revised version of your code has been provided below. The adjustments include adding the fio v-model and merging your computed and data properties. Congratulations on making progress!

Check out the working example here: https://jsfiddle.net/vpk02stu/5/

In compliance with stackoverflow standards, refer to the code snippets below:

JavaScript

new Vue({
    el: '#forms',
    data: { email: '', fio: ''},
    computed: {
        isEmailValid: function isEmailValid() {
            return (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(this.email)
            );
        },
        isFioValid: function isFioValid() {
            return (/\w+[ ]+\w+[ ]+\w+/.test(this.fio)
            );
        }
    }
});

HTML

<div class="container" id="forms">
  <h3 style="text-align:center;">Fill the fields</h3>
        <form class="form-signin">

          <label for="inputFIO" class="sr-only">ФИО</label>
          <input type="text" id="inputFIO" class="form-control" placeholder="Surname and Name" required v-model="fio">
          <div class="error" v-show="fio && !isFioValid"><span style="color:red;">Input name and surname</span></div>

          <label for="inputEmail" class="sr-only"></label>
          <input type="email" id="inputEmail" class="form-control" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3a273e322f333a1f3b30323a31713c3032">[email protected]>
          <div class="error" v-show="email && !isEmailValid"><span style="color:red;">Enter a valid e-mail address</span></div>

          <label for="inputText"></label>
    <textarea class="form-control" id="inputText" rows="4"></textarea>

          <button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
        </form>
      </div>

Style

body {
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #eee;
}

.form-signin {
  max-width: 430px;
  padding: 15px;
  margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin {
  margin-bottom: 10px;
}
.form-signin .checkbox {
  font-weight: normal;
}
.form-signin .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="email"] {
  margin-bottom: 10px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="text"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}


.btn {
max-width: 200px;
margin: 0 auto;
margin-top: 15px;
}

Answer №2

While Angular provides a built-in option for form validation, Vue falls short in this area with limited functionality. To enhance form validation capabilities in Vue applications, users can opt to install the Vuelidate package.

Understanding Vuelidate
As described on the Vuelidate website:
“Vuelidate 2 offers a straightforward yet robust model-based validation solution for both Vue.js 3 and Vue 2.x.”

This package enables the use of pre-built validators along with the ability to create custom ones

Installation Steps

npm install @vuelidate/core @vuelidate/validators

For further information:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Foundation 6 not triggering the change.zf.slider event

Hey there, this is my first time posting and I could really use some help... I'm struggling to make the $("[data-slider]").on('change.zf.slider', function(){}); event trigger. I've attempted using the id of the element like so $(" ...

What is the process for setting up a new router?

When it comes to templates, the vuestic-admin template from https://github.com/epicmaxco/vuestic-admin stands out as the perfect fit for my needs. However, I have a specific requirement to customize it by adding a new page without displaying it in the side ...

Navigating through various features in nodejs / expressjs

Managing multiple functions in nodejs/expressjs can be a bit confusing for those used to PHP. In PHP, you simply call one function after another, but in node, things work differently with callbacks and potential errors related to undefined variables. Her ...

Top Method for Incorporating Syntax Highlighting into Code Blocks - React Sanity Blog

I'm currently exploring the most effective method to incorporate syntax highlighting into my react sanity.io blog. Here's a look at the article component I've developed using react: import React, {useEffect, useState} from "react"; import ...

Limiting access to multiple Node.js applications on a machine with multiple IPv4 addresses

Setting up a Ubuntu 19.10 machine with one to two wired network interfaces and multiple IP addresses assigned to each interface, for example, 10.0.0.1 and 10.0.0.2. Is there a way to run two identical Node.js applications where the first one uses the IP a ...

Combine PHP, jQuery, and AJAX to retrieve multiple values simultaneously

I have been using jQuery AJAX for my projects. When I make an AJAX call to a PHP page, it normally returns a single value to the success function of AJAX. However, I am now looking to retrieve multiple data individually. How can I achieve this? This is th ...

Unable to execute internal functional tests due to this error: [POST http://localhost:4444/wd/hub/session] unable to connect - ECONNREFUSED

Currently working with node 0.12 and intern 3 in order to execute functional tests, but encountering the following error: SUITE ERROR Error: [POST http://localhost:4444/wd/hub/session] connect ECONNREFUSED at Server.createSession <node_m ...

Executing a single command using Yargs triggers the execution of multiple other commands simultaneously

I've been diving into learning nodejs and yargs, and I decided to apply my knowledge by creating a command-line based note-taking app. The structure of my project involves two files: app.js and utils.js. When I run app.js, it imports the functions fr ...

Ways to alter a PHP variable with each AJAX request

Utilizing AJAX to dynamically add more content to an image gallery. I'm passing a PHP variable to dictate the current page number and other necessary data. Each time new data is fetched via AJAX, I want to increment the page variable by one to fetch ...

Tips for creating a responsive input field within a navbar

Can anyone assist me with setting the input field width in my navbar to adjust to the remaining width of the navbar and be responsive to different device sizes? I need the input field to dynamically change its width based on the screen size. Any help would ...

Unresolved error causing promise to throw an exception

My code is causing an error when resolve is called: Possibly unhandled Error: undefined at Promise$_rejecter (c:\projects\Test\promiseftp\node_modules\bluebird\js\main\promise.js:602:58) at WriteStream.<a ...

Transferring data between modules in nodejs

Within my custom module, there is a method designed to query the database and check if a given username exists. I need certain values to be returned in order to determine the query result at a higher level. var findUserbyUsername=function(username) { ...

What's the best way to vertically center a div with a 100% width and a set padding-bottom on the screen?

I am struggling with positioning the following div on my webpage. .div { width:100%; padding-bottom:20%; background-color:blue; } <div class="div"></div> I have been searching for a solution to vertically center this responsive div on my web ...

Is it possible to generate a "pop-up" window upon clicking on the register button?

As a backend programmer, I'm looking to create a popup window that appears in front of the current window when users click "register", eliminating the need for redirection to another page. I believe you understand the concept. How can I achieve this? ...

Why is React JS unable to discover my exported modules?

Upon running my React app, the console displayed the following error message: Failed to compile. ./src/components/login/index.js Attempted import error: 'Login' is not exported from './login'. Here is an overview of the folder struct ...

Searching for nested objects while adhering to JSLint guidelines can be achieved by following

I have a structured object and I'm trying to locate the product using its ID. 0 :{ id: 0, title: 'xxxx', url: "www.test.com" quantity: 100 }, 1 :{ id: 10, title: 'xxxx', url: "www.test.com" ...

Tips for concealing the navbar in bootstrap-vue when it is collapsed

Is there a CSS-only solution in BootstrapVue to hide text in the navbar when it collapses? I tried using .d-none .d-sm-block, but it doesn't work when the toggler collapses the navigation. jQuery solutions won't work with the Vue wrapper of boots ...

Tips on specifying a default value when receiving data from an API

I am working with a dropdown list that is populated from an API call. Here is my code snippet: <label>User Code:</label> <select ng-options="c as c.User for c in userList" ng-model="selectedUser" id="search3"> </select> To fet ...

React.js Filter Component

I'm currently trying to create a filter for my "localtypes", but I'm encountering an issue where the console in my browser is displaying an empty array. My goal is to access the localtypes properties of the API that I am working with. I attempte ...