Validate e-mail using REGEX with VUE3!

Validate e-mail using REGEX with VUE3!

ยท

1 min read

This is one of the questions many people have when starting out in the world of VUE. How to validate an email before sending it to an API.

The process is simple, and once it gets into your mind, you'll never forget this procedure that practically every system has:

So let's go, the first code you need to create is your input in the VUE template.

Hope this helps! ๐Ÿ˜Š

<template>
  <input type="text" :value="email" @input="updateEmail" />
  <p v-if="isValidEmail">E-mail correct!</p>
</template>

Next, we will create the script part in VUE3 using the COMPOSITION API.

<script setup>
import { ref, watch } from 'vue';

const email = ref('');
const isValidEmail = ref(false);
// This WATCH check if there are changes in ref e-mail
// and check using REGEX script if isvalid!
watch(email, (newEmail) => {
  const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  isValidEmail.value = regex.test(newEmail);
});
// @input function is called here!
function updateEmail(event) {
  email.value = event.target.value;
}
</script>

Now when the regex.test is true... will change the isValidEmail and you can send your e-mail to some API for example or make something in your UI.

Very simple right?

Thanks, see you next lesson!

Eduardo Burko - Senior Vue Developer at Grupo BRT

ย