Validating emails using Vue.js

After spending a solid 24 hours working with Vue, I realize there may be some gaps in my knowledge. Despite my efforts to search for solutions, I suspect that my lack of understanding on basic principles is hindering me.

One issue I've encountered is that I have a modal that pops up when a button is clicked. Within this modal, there's a form with an email input field. While I successfully implemented the modal functionality, I'm facing an obstacle where nothing happens when an incorrect email format is entered.

Below is the code snippet for the component:

<template>
<div>
  <!-- Aside -->
  <aside class="aside">
    <button class="aside__btn button" @click="showModal = true">
      Send Me The Tips
    </button>
  </aside>

  <!-- Modal -->
  <div class="modal" v-if="showModal">
    <div class="modal-container">
      <a href="#" class="close" @click="showModal = false"></a>

      <p class="modal__steps">Step 1 of 2</p>
      
      <div class="relative">
        <hr class="modal__divider" />
      </div>

      <div class="modal__heading-container">
         <p class="modal__heading">Email Your Eail To Get <span class="modal__heading-span">Free</span>
         </p>
         <p class="modal__heading">iPhone Photography Email Tips:</p>
      </div>

      <form> 
        <input for="email" type="email" placeholder="Please enter your email here" required v-model="email">
        <span class="floating-placeholder" v-if="msg.email">{{msg.email}}</span>
        <button class="modal__button button">Send Me The Tips</button>
      </form>
    </div>
  </div>
  </div>
</template>

<script>
  export default ({
    data () {
      return {
        showModal: false,
        email: '',
        msg: [],
      }
    }, 
    watch: {
      email(value) {
        // binding this to the data value in the email input
        this.email = value;
        this.validateEmail(value);
      }
    },
    methods: {
      validateEmail(value){
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(value))
    {
      this.msg['email'] = '';
    } else{
      this.msg['email'] = 'Please enter a valid email address';
    } 
      }
    }
  })
</script>

For context, I am using Laravel in this project.

Answer №1

To improve the functionality, I suggest removing the watch and instead adding an event listener on blur:

<input for="email" type="email" placeholder="Please enter your email here" required v-model="email" @blur="validateEmail">

Additionally, make sure to update the validateEmail method like this:

validateEmail() {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.email)) {
        this.msg['email'] = 'Please enter a valid email address';
    } else {
        this.msg['email'] = '';
    }
}

If needed, you could also consider changing the event listener to @change for a different approach.

Answer №2

If you're looking for a solution to handle form validation, Vuelidate is worth exploring. Check out the example below:

<template>
    <div>
        <input
            class="rounded shadow-sm border border-warning"
            v-model="form.email"
            placeholder="E-mail"
            @input="$v.form.email.$touch"
            :state="$v.form.email.$dirty ? !$v.form.email.$error : null" />
    </div>
</template>

<script>
import {required, email} from "vuelidate/lib/validators";
  
export default {
  data() {
    return {
      form: {
        email: null,
      }
    };
  },
  validations: {
    form: {
      email: {
        required,
        email
      }
    }
  },
};
</script>

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

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

Guidelines on integrating Admob into Ionic framework

I tried following the steps outlined in this post: AdMob not loading ads in ionic/angular app After running the app using "ionic build ios && ionic emulate ios," I still see no ads, no black bar, nothing at all. Can someone help me figure out wha ...

What advantages does leveraging GraphQL with React offer compared to using GraphQL with Vue, Ember, or Angular?

Curious if there are any advantages to combining GraphQL, created by Facebook, with React? Or is it better to use a different JavaScript framework like Vue, Angular, or Ember instead? ...

adjustable height of a table (vuetify)

Main.vue <template> <v-app id="inspire"> <v-navigation-drawer v-model="drawer" app > <v-list dense> <v-list-item link> <v- ...

Exploring the power of D3's nested appends and intricate data flow

Currently diving into the world of D3, I've encountered a perplexing issue that has yet to be resolved. Unsure if my confusion stems from a lack of familiarity with the library or if there's a key procedure eluding me, I feel compelled to seek gu ...

What are the compatibility considerations for npm packages with Angular 2? How can I determine which packages will be supported?

When working with Angular 2, do NPM packages need to be modified for compatibility or can any existing package work seamlessly? If there are compatibility issues, how can one determine which packages will work? For instance, let's consider importing ...

Is there a way in Javascript or JQuery to determine if a function is currently executing, or is there a way to tap into a return event?

Let me paint a picture of a common scenario: there's a form with numerous inputs (around 60-70). Each input must undergo validation, and if it is invalid, the form returns false. To prevent multiple AJAX requests with visual feedback, I need to safegu ...

What is the best way to obtain a unique dynamic id?

This is the unique identifier retrieved from the database. <input type="hidden" name="getID" value="<?php echo $row['ID']; ?>"> <input type="submit" name="getbtn" value="Get ID"> How can I fetch and display the specific dynami ...

Error encountered: Attempting to render an object as a react component is invalid

I am attempting to query data from a Firestore database. My goal is to retrieve all the fields from the Missions collection that have the same ID as the field in Clients/1/Missions. Below, you can find the code for my query: However, when I tried to execu ...

Image not showing up when using drawImage() from canvas rendering context 2D

Need help with drawImage() method in JavaScript <head> </head> <body> <script type = "text/javascript"> var body, canvas, img, cxt; body = document.getElementsByTagName("body" ...

How to implement a form in PHP that doesn't refresh the page upon submission

I am having an issue with this ajax code. I know it works, but for some reason it's not submitting. <script type="text/javascript"> $(function(){ $('input[type=submit]').click(function(){ $.ajax({ type: "POST", ...

Looking to display parent and child elements from a JSON object using search functionality in JavaScript or Angular

I am trying to display both parent and child from a Nested JSON data structure. Below is a sample of the JSON data: [ { "name": "India", "children": [ { "name": "D ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Creating captchas seems like a mistake in reasoning to me

I am encountering an issue with my code. I created a basic newbie-level captcha using Javascript. Below is the code snippet: <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <h1>T ...

tsc and ts-node are disregarding the noImplicitAny setting

In my NodeJS project, I have @types/node, ts-node, and typescript installed as dev dependencies. In the tsconfig.json file, "noImplicitAny": true is set. There are three scripts in the package.json file: "start": "npm run build &am ...

What is the best way to pass a variable between clusters in a Node.js application?

I have implemented clusters in my express application, where the master node has a caching system with a variable that needs to be shared across worker nodes. I am looking for a way to achieve this without using a physical datastore. Can the following ap ...

The function window.scrollBy seems to be causing a conflict with jjmslideshow, resulting in the page being unable to

I wrote a simple script to create a "smooth scroll" effect when a specific link is clicked: (function() { 'use strict'; // Checking for compatibility if ( 'querySelector' in document && 'addEventListener' in window ...

Error encountered when attempting to retrieve posts using Axios: Unexpected symbol detected, expected a comma (25:4)

I've been working on implementing an axios getPosts function, but I keep encountering a syntax error that I can't seem to locate in my code. getPosts = async () => { let data = await api.get('/').then(({ data }) => data); ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...

Troubleshooting issues with the sidebar navigation in Laravel project using Vue and AdminLTE

I successfully installed AminLte v3 via npm in my Laravel + vue project and everything is functioning properly. However, I am facing an issue when I attempt to click on the main menu item in the Side navbar that is labeled as <li class="nav-item has-tr ...