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 >
<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';
}
},
}
CodePudding user response:
This may work fine
<template>
<div >
<input
ref="email"
v-model="email_p"
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).
CodePudding user response:
Instead of ref you can pass value to your method or check this.email_p
:
new Vue({
el: '#demo',
data() {
return {
email_p: "[email protected]",
other: ""
}
},
methods: {
validateMail(val){
let value = val
// or without passing value
// let value = this.email_p
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
console.log("passed")
} else {
console.log('Enter a valid email');
}
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div >
<input type="email" @blur="validateMail(email_p)" v-model="email_p" name="email"/>
<input type="text" v-model="other" />
</div>
</div>