payose
payose

Reputation: 23

how can i to make @blur event work properly - Nuxtjs

I am trying to trigger a function that validates an input field when it loses focus using nuxtjs. When I focus out of the input field, the function isn't triggered but gets triggered when I focus in and start typing in another or the same input field.

<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';
            }
        },
}

Upvotes: 1

Views: 1694

Answers (1)

kissu
kissu

Reputation: 46612

This may work fine

<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 passed
      } else {
        this.msg.email = 'Enter a valid email'
      }
    },
  },
}
</script>

You don't need to use $refs to access the element, you can access the event directly.
If you want to get the value via $refs, you would need to wait for a full tick to trigger, to get the actual new value. Hence use the event passed by @blur, simpler, cleaner and less messy.

Also, value.target.value is important because it's receiving an event and not the HTML element itself.

PS: the event can also be written as @blur="validateMail($event)" if you want to be more explicit but it's not mandatory (it's passing it by itself already).

Upvotes: 2

Related Questions