What steps can I take to ensure that the @blur event functions correctly in Nuxtjs?

I'm attempting to implement a function that validates an input field when it loses focus in nuxtjs. Strangely, the function doesn't trigger when I move out of the input field, but does trigger when I move into another input field and start typing.

<div class="control">
  <input class="input" type="text" ref="email" @blur="validateMail()" v-model="email_p" name="email" />
</div>

This is the function call

 methods: {
        validateMail(){
            let value = this.$refs.email.value
            let mailformat = /^(([^<>()[\]\\.,;:\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,}))$/

            if (value.match(mailformat)) {
                //validation passed
            } else {
                this.msg.email = 'Enter a valid email';
            }
        },
}

Answer №1

This solution should work effectively

<template>
  <div class="control">
    <input
      ref="email"
      v-model="email_p"
      class="input"
      type="text"
      name="email"
      @blur="validateMail"
    />
    message: {{ msg.email }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      email_p: '',
      msg: {
        email: '',
      },
    }
  },
  methods: {
    validateMail(value) {
      const mailformat =
        /^(([^<>()[\]\\.,;:\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,}))$/

      if (value.target.value.match(mailformat)) {
        // validation successful
      } else {
        this.msg.email = 'Please enter a valid email'
      }
    },
  },
}
</script>

You can directly access the event without using $refs.
If you prefer to get the value through $refs, ensure to wait for a complete tick to trigger in order to retrieve the updated value accurately. Therefore, it's simpler and cleaner to use the passed event from @blur.

Moreover, remember that value.target.value is essential as it receives the event itself, not just the HTML element.

PS: You can also specify the event explicitly as

@blur="validateMail($event)"
for clarity, although it's not required (it already passes it by default).

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

The alterations made to a single dropdown option are causing ripple effects across all other dropdowns

There is an add button that continuously adds a div container containing two dropdowns. The selection in one dropdown affects the data in the other dropdown. When the add button is clicked, a second div with both dropdowns is added. However, changing the ...

Having issues sending multiple variables to PHP through Ajax

Trying to pass three variables through the URL using Ajax - one constant and two from a date picker. The constant passes fine, but the date variables are only passing as their names. Here's the code for the date pickers: <tr> ...

Any additional characters needed?

Currently, I am working on developing a word unscrambler that takes a scrambled word as input and then unscrambles it. The functionality is mostly working well, although I have come across a situation where some extra characters are slipping through the pr ...

How to effectively implement light and dark themes using SCSS colors?

Currently, I am utilizing Vue.js and SCSS along with PrimeVue and Element plus, where I am importing their variables. My objective is to dynamically change the theme color. In my dark-variables.scss file, I have defined various color variables for differe ...

Setting the main color in Vue based on certain conditions

After developing a Vue app as a reusable library and setting the global $brand-color variable in the SCSS file to define the main color theme of the app, I encountered an issue when trying to integrate it for a new client who required a different brand col ...

How to get an empty object as a response in a NODE.JS request?

For some reason, I am attempting to send an object to my backend. Even though I can retrieve valuable information from my network's payload, my req.body consistently returns an empty object. View my issue ...

The outcome of the method is not being displayed

I have an issue with updating the value of an array method in an HTML file using the p tag. The problem is that even though the method returns the value, the HTML doesn't update to reflect the new value. Strangely, when using console.log, the value ap ...

AppProps in Next.js - Ensure that you have the correct loader set up to handle this specific file type as there are currently no loaders configured for processing it

I've encountered an issue while working on a Next.JS 13.5.6 application in development mode. When I try to connect to the site, I receive an error message. However, everything works fine when I switch to production mode after building and starting the ...

"Presenting Invoice Information on an Invoice Template: A Step-by-Step Guide

Currently, I am working with Laravel 5.7 and VueJs 2.5.*, where I have a table of invoices. My goal is to create a new component that will display a specific invoice based on user selection, allowing them to view or print the chosen invoice. I am still ex ...

Diagnosing circular JSON can be a challenging task

Encountering an issue in my error handler with the following message: Uncaught TypeError: Converting circular structure to JSON. I suspect that there might be an additional exception thrown within the JSON.stringify call leading to this error. It's p ...

Displaying different elements using an anchor <a> tag

Within this example, I've created two functional components that mimic separate pages with differently colored <div> boxes. const Home = () => <div style={{background:'red', height: 100, width: 100}}></div>; const ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

Creating numerous duplicates of a highly nested immutable Object can be done by using a combination of spread operators

I am currently working on retrieving data from firebase/firestore using Javascript. I have created a function where I retrieve my products collection and pass this data to the React state.products by utilizing the setState() method. My objective is to tra ...

Using jQuery and regex to validate a long string containing lowercase letters, uppercase letters, numbers, special characters, and

Good day, I've been struggling with jquery regex and could really use some assistance. I've been stuck on this since last night and finally decided to seek help :) Here is my regex code along with the string stored in the 'exg' variabl ...

Removing data from a table using an identifier in Typescript

Recently, I have made the switch from using Javascript to TypeScript. However, I am facing an issue while trying to delete data from a table in my code. Whenever I attempt to delete data, I encounter this error message: Property 'id' does not e ...

Struggling to incorporate blocks into Jade for Express. Encountering errors like "Max Stack Size Exceeded" and issues with setHeader

I am currently using Express along with a simple express-generator server that I created. My first task was to focus on creating the view layout and extending the index page, but unfortunately, I have encountered some challenges. Throughout my process, I& ...

Swapping out meshes on the fly using three.js動态替换单个网格与

I have a unique idea for a breakout game where the paddle is shaped like a piece of roof trim, with its shape changing based on the pitch of the roof. Hitting special bricks will alter the pitch variable, thus changing the "steepness" of the paddle. Howeve ...

Can you explain the significance of "mongodb is not a function"?

As a novice in the world of programming, I am currently diving into a web development course. However, I encountered an error while trying to connect to a database I created. The error message states that "mongodb.connect is not a function." Below is the ...

Develop an event listener in a React Component that watches for changes

I have a React component and I am looking to implement an "onChange" event that can be detected by another component in the application. const FirstComponent = () => { // Implement functionality // How can I create an event here that can be detec ...

Sort slider items using Show/Hide feature in bxSlider

I am using a bxslider on my website with specific settings: $('#carousel').bxSlider({ slideWidth: 146, minSlides: 2, maxSlides: 6, speed:500, adaptiveHeight: true, moveSlides:3, infiniteLoop : false, hideContr ...