Reputation: 399
I have been working with Vue for 24 hours now, so forgive the ignorance. I have searched around and I'm getting close, but I'm sure it's my lack of understanding and basic principles.
I have a modal that opens when a button is clicked. This modal displays a form with an email input. I managed to get the modal working, but nothing happens when I type in an incorrect email.
Here's my code 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>
<!-- <span class="floating-placeholder">Please enter your email here</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>
I'm using Laravel if that's of importance.
Upvotes: 8
Views: 43857
Reputation: 21
You could also checkout Vuelidate which handles form validation. For example:
<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>
Upvotes: 2
Reputation: 1200
I would delete the watch and add an event listener on blur like so:
<input for="email" type="email" placeholder="Please enter your email here" required v-model="email" @blur="validateEmail" >
and update the validateEmail method like so :
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'] = '';
}
}
You could also change the event listener to change @change
if it serves your needs better.
Upvotes: 19