Email Validation Regex Fix
March 8, 2025 · AI Conversations
<script>
import { ref } from "vue";
import { useForm, useField } from 'vee-validate'
import IconLoading from '../components/icons/IconLoading.vue';
import SingleColumn from '../layouts/SingleColumn.vue';
const { handleSubmit, handleReset } = useForm({
validationSchema: {
name (value) {
if (value?.length >= 2) return true
return 'Name needs to be at least 2 characters.'
},
email (value) {
if (/^[a-z.-]+@[a-z.-]+.[a-z]+$/i.test(value)) return true
return 'Must be a valid e-mail.'
},
password (value) {
if (value?.length >= 6) return true
return 'Password needs to be at least 6 characters.'
}
},
})
const name = useField('name')
const email = useField('email')
const password = useField('password')
const submit = handleSubmit(values => {
alert(JSON.stringify(values, null, 2))
})
const user = ref({
username: "",
email: "",
password: "",
});
const loading = ref(false);
const message = ref("");
const showPassword = ref(false);
const createUser = async () => {
loading.value = true;
const apiUrl = "https://autohauslange.carmar.digital/wp-json/wp/v2/users";
const adminUsername = "plstr-admin";
const applicationPassword = "MrYNs0r68Hb7ywed01JmiX7d";
// Encode credentials for Basic Auth
const authHeader = `Basic ${btoa(`${adminUsername}:${applicationPassword}`)}`;
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Authorization": authHeader,
"Content-Type": "application/json",
},
body: JSON.stringify(user.value),
});
const result = await response.json();
if (response.ok) {
message.value = `User ${result.username} created successfully!`;
} else {
message.value = `Error: ${result.message}`;
}
} catch (error) {
message.value = `Request failed: ${error.message}`;
loading.value = false;
} finally {
loading.value = false;
}
};
</script>
Register
submit
clear
we are entring correct email still saying email not valid
/^[a-z.-]+@[a-z.-]+.[a-z]+$/i
### Problems with this regex:
1. It does not allow numbers in the email (e.g., `user123@example.com`).
2. It does not allow uppercase letters before `@`, though you're using `/i` to make it case-insensitive.
3. It does not allow subdomains (e.g., `user@mail.co.uk`).
4. It does not allow underscores (`_`), which are valid in emails.
5. It does not support multiple dots in domain names (e.g., `user@sub.example.com`).
### **Fix**
Use a better regex for email validation:
email(value) {
if (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/i.test(value)) return true
return 'Must be a valid e-mail.'
}
### **Explanation of the improved regex**
– `^[a-zA-Z0-9._%+-]+` → Allows letters, numbers, dots (`.`), underscores (`_`), percentage (`%`), plus (`+`), and hyphen (`-`) in the username part.
– `@` → Requires an `@` symbol.
– `[a-zA-Z0-9.-]+` → Allows domain names with letters, numbers, dots, and hyphens.
– `.[a-zA-Z]{2,}$` → Ensures the domain extension (TLD) is at least two characters long (e.g., `.com`, `.net`, `.co.uk`).
This should resolve the issue and correctly validate emails like:
✅ `test@example.com`
✅ `john.doe_123@mail.co.uk`
✅ `user.name+filter@gmail.com`
✅ `name@sub.example.com`
Try updating your validation function with this and test again. 🚀
—
### **1. Update the `validationSchema`**
Modify the `validationSchema` to include a `confirmPassword` field that checks if it matches the `password` field.
const { handleSubmit, handleReset } = useForm({
validationSchema: {
name (value) {
if (value?.length >= 2) return true;
return 'Name needs to be at least 2 characters.';
},
email (value) {
if (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/i.test(value)) return true;
return 'Must be a valid e-mail.';
},
password (value) {
if (value?.length >= 6) return true;
return 'Password needs to be at least 6 characters.';
},
confirmPassword (value, { password }) {
if (value === password) return true;
return 'Passwords do not match.';
}
}
});
—
### **2. Add the `confirmPassword` field**
Now, add the `useField` hook for `confirmPassword`:
const name = useField('name');
const email = useField('email');
const password = useField('password');
const confirmPassword = useField('confirmPassword');
—
### **3. Update the template to include the Confirm Password field**
Modify your “ inside the `template` to include the Confirm Password field.
<v-text-field
v-model="confirmPassword.value.value"
:type="showPassword ? 'text' : 'password'"
:error-messages="confirmPassword.errorMessage.value"
prepend-inner-icon="mdi-lock"
:append-inner-icon="showPassword ? 'mdi-eye-off' : 'mdi-eye'"
@click:append-inner="showPassword = !showPassword"
label="Confirm Password"
/>
—
### **Final Steps**
✅ Now, when a user enters a password, they must re-enter it in the "Confirm Password" field.
✅ If they don’t match, they’ll see the error message: **"Passwords do not match."**
✅ Your validation will now be stronger! 🚀
Try this and let me know if you need any improvements. 🔥
—
### **Solution: Use `values` in Validation Schema**
Update your `useForm` setup like this:
const { handleSubmit, handleReset, values } = useForm({
validationSchema: {
name(value) {
if (value?.length >= 2) return true;
return "Name needs to be at least 2 characters.";
},
email(value) {
if (/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/i.test(value))
return true;
return "Must be a valid e-mail.";
},
password(value) {
if (value?.length >= 6) return true;
return "Password needs to be at least 6 characters.";
},
confirmPassword(value) {
if (value === values.password) return true;
return "Passwords do not match.";
},
},
});
—
### **2. Register the `confirmPassword` Field**
Now, make sure you've added `useField` for `confirmPassword`:
const name = useField("name");
const email = useField("email");
const password = useField("password");
const confirmPassword = useField("confirmPassword");
—
### **3. Update Template**
Modify your form to include the Confirm Password field:
<v-text-field
v-model="confirmPassword.value.value"
:type="showPassword ? 'text' : 'password'"
:error-messages="confirmPassword.errorMessage.value"
prepend-inner-icon="mdi-lock"
:append-inner-icon="showPassword ? 'mdi-eye-off' : 'mdi-eye'"
@click:append-inner="showPassword = !showPassword"
label="Confirm Password"
/>
—
### **Why This Works?**
✅ Now, `confirmPassword` has access to `values.password`, so it can compare correctly.
✅ If passwords don't match, it will show **"Passwords do not match."**
✅ If both fields are valid, the form will submit successfully.
Try this and let me know if you need any improvements! 🚀🔥