I am use vuetify form validation with rules I have a problem in asynchronous validation of email existed
This code for rule:
data () {
return {
rules: {
email: value => {
const pattern = /^(([^<>()[\]\\.,;:\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,}))$/
return pattern.test(value) || 'Invalid e-mail.'
},
mailExist: value => (this.emailExists(value) === 'valid Email Address') || 'Error'
},
}
},
This code for method run to make sure mailExist validation:
methods: {
emailExists: function (val) {
if (val !== '') {
axios.get(`email_validation.php?empemail=${val}`)
.then(response => {
console.log(response.data)
return response.data
})
.catch(err => {
console.log(err)
})
}
},
},
The result always be 'Error' but the response from api it's True, As in the picture: Picture
This code for PHP API:
<?php
require "../includes/DbOperations.php";
$result = array();
if ($_SERVER['REQUEST_METHOD'] == 'GET')
{
if (isset($_GET['empemail']))
{
$db = new DbOperations();
if (filter_var($_GET['empemail'], FILTER_VALIDATE_EMAIL))
{
if ($db->email_validation($_GET['empemail']))
{
$result = "This Email Already Exist";
}
else
{
$result = "valid Email Address";
}
}
else
{
$result = " Invalid Email Address";
}
}
else
{
$result = "Invalid Inputs";
}
}
else
{
$result = "You Do Not Have Permission";
}
echo json_encode($result);
Thankyou ..
I solved the problem this way ..
In the email field:
<v-text-field
label="Email Address"
type="email"
class="purple-input"
:rules="[rules.email, rules.existingMail]"
v-model="email"
:messages="mailMessage"
@keyup="emailExists()"
/>
Data and rules object:
data () {
return {
email: '',
rules: {
required: value => !!value || 'Required.',
email: value => {
const pattern = /^(([^<>()[\]\\.,;:\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,}))$/
return pattern.test(value) || 'Invalid e-mail.'
},
existingMail: () => true || this.mailMessage
},
mailMessage: '',
}
},
In the methods:
methods: {
emailExists: function () {
if (this.email !== '') {
axios.get(`email_validation.php?empemail=${this.email}`)
.then(response => {
if (response.data !== 'valid Email Address') {
this.mailMessage = response.data
this.rules.existingMail = false
} else {
this.mailMessage = ''
this.rules.existingMail = true
}
})
.catch(err => {
console.log(err)
})
}
},
}
Maybe there is a better way to fix this, but my method works fine..