Skip to content

Instantly share code, notes, and snippets.

@Whats-A-MattR
Last active October 2, 2022 16:00
Show Gist options
  • Save Whats-A-MattR/7ff5b15d0d4ef02e2618cc3e1ea71a49 to your computer and use it in GitHub Desktop.
Save Whats-A-MattR/7ff5b15d0d4ef02e2618cc3e1ea71a49 to your computer and use it in GitHub Desktop.
Vue Email Validation using Vanilla JS / Regex
// this very simple example is referencing bootstrap, but the method will be the same if using other presentation frameworks
<template>
<div>
<div class="floating-form mx-auto">
// create a simple input field, but bound the imput to data property with v-model
<input id="emailaddress" type="email" class="form-control" aria-describedby="email" placeholder="Your Email Address" v-model="mailAddress" />
// create a button that has an @click function, and where disabled is bound to the email_isValid computed property - this means the user will not be able to click when the email is not determined to be valid by the regular expression evaluation
// note that the boolean is flipped here using a '!', this is so that when the email not yet entered or evaluated as invalid the expected value of false, gets set to true to enable the 'disabled' attribute - and vice versa
<b-button @click="submitemail" :disabled="!email_isValid" />
</div>
</div>
</template>
// here we define our data properties, computed properties, and methods (as well as much more that isn't relevant to this gist)
<script>
export default {
name: 'demo',
data() {
return {
// your v-bind for a form input etc.
mailAddress: ''
}
},
computed: {
// as this is a computed property, any time mailAddress is updated, this property is re-evaluated - which is why we're using a computed, rather than the method directly
email_isValid() {
// run this whenever mailAddress is updated
return evalEmail()
}
},
methods: {
evalEmail() {
// defining out regular expression, storing the object
const mailRegex = new RegExp(/^(([^\<\>\(\)\[\]\\\^\.\,\;\:\`\{\}\?\!\|\~\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,}))$/)
// testing our 'mailAddress' against the regex object
return mailRegex.test(this.mailAddress)
},
submitEmail() {
// stop page reloading on submit
event.preventDefault()
//do your things
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment