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

Having issues with regEX functionality in an Angular form

I need to validate a phone number using regEX. My criteria is as follows: 10 digits alpha/numeric, where an Alpha CHAR is in the 4th position (excluding hyphens). For example: 586R410056  NNN ANN NNNN  (NNN) ANN NNNN  NNN-ANN-NNNN  (NNN) AN ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

Refresh a div element automatically with information from a different webpage using jQuery

I've been attempting to automatically reload a page and fetch new data every 10 seconds, or even less. However, the codes I've tried so far have not been successful. Here is my current approach... // script // <script> $(document).rea ...

Ways to stop CKEDITOR from automatically saving textarea or contenteditable content

I've integrated the CKEDITOR plugin for a format toolbar feature on my web application. It seems that the message shown above is a default one provided by CKEDITOR. My goal is to have users start with a blank textarea every time they visit the page, ...

Refresh your webpage automatically without the need to manually refresh after clicking a button using AJAX in HTML and PHP!

One issue I'm facing is that the page doesn't auto-refresh, although it loads when I manually refresh it. Below you can find my HTML and AJAX code along with its database details. The Trigger Button <?php $data = mysqli_ ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...

Changing Highcharts Donut Chart Title Text via Legend Item Click in React

Utilizing React. In my Highcharts donut chart, there are 5 legend items of type 'number' and a 'title text' (also type: number) displayed at the center. The title text represents the sum of all the legend items. However, when I click o ...

What is the best way to access the inner html of every cell within a table row that I have selected?

I want to implement a feature on my website where users can click a "save" button on a specific row in a table and save the entire row's innerHtml onto another page as their favorite hiking trails. I've been trying to achieve this by adding clic ...

Establishing global credentials in VueJS using Axios

When working in main.js, I included the following code: axios.defaults.withCredentials = true; Although this should make it work, I found that the cookies were not being sent to the back end. I inspected the request header and noticed something strange: ...

Deactivate interactive functions on the mat-slider while preserving the CSS styling

I'm attempting to create a mat-slider with a thumb label that remains visible at all times. Below is my mat-slider component: <mat-slider class="example-margin" [disabled]="false" [thumbLabel]="true" [tickInterval]="tickInterval" ...

Having trouble reaching the link using my controller in a jhipster application

I've been working on a project with jhipster and recently created a test controller to check if everything is functioning properly. Take a look at my test controller code: @RestController @Configuration public class TestController { private stat ...

Is there a way for me to choose all the classNames that conclude with a specific word within the MUI sx property?

I am currently working with MUI and I have a need to modify certain properties that are prefixed with random IDs. How can I target, for instance, the first one using: '& endsWith(MuiAccordionDetails-root)' I wish to achieve this because the ...

Filtering Sails.js query model based on a collection attribute

Imagine I have these models set up in Sails.js v0.10: Person.js module.exports = { attributes: { name: 'string', books: { collection: 'book', via: 'person' } } }; Book.js module.exports = { ...

Aligning a navigation bar with a hamburger menu in the center

I recently implemented a hamburger menu with some cool animations into my site for mobile devices. Now, I am facing the challenge of centering the menu on desktop screens and it's proving to be tricky. The positioning is off, and traditional methods l ...

Execute identical task using a for loop in JavaScript

Here is a sample code snippet: var seats = [] for (a = 0; a <= seatsNumFront; a++) { seats.push(new Seat((a * xPad) + 300, 60, 30, 30, id++, "A", a, "#998515")) } for (b = 0; b <= seatsNumFront; b++) { seats.push(new Se ...

Next.js encountered an API resolution issue while uploading a file, resulting in no response being

Even though my code is functioning properly, a warning appears in the console: The API call was resolved without sending any response for /api/image-upload This particular endpoint is responsible for uploading an image to Digital Ocean's object sto ...

What is the process for transforming a nested dictionary in JSON into a nested array in AngularJS?

I am looking to create a form that can extract field values from existing JSON data. The JSON I have is nested with dictionary structures, but I would like to convert them into arrays. Is there a way to write a recursive function that can retrieve the key ...

Next.js directs API requests to the root URL

I'm currently working with an API handler pages/api/[slug]/[uid].ts My goal is to redirect the requests to the main root of my application, specifically: http://localhost:3000/[slug]/[uid] What steps do I need to take in next.config in order to mak ...

Tips for customizing the CSS file of a React component imported from a UI framework

As I embark on building a large application utilizing React, I find myself navigating the new territory of React philosophy coming from a background of Css+Js+jQuery methods. One key requirement for my project is a reliable UI framework that aligns with Go ...

Are your GetJSON requests failing to execute properly?

I have a code snippet that executes in a certain sequence and performs as expected. <script> $.getJSON(url1, function (data1) { $.getJSON(url2, function (data2) { $.getJSON(url3, function (data3) { //manipulate data1, data2, ...