I’m trying to use Javascript for a simple form validation. In this case, I have an email text input and I want it to error if the email is not a valid email or the email address is already taken. The valid email part is erroring fine, but the email address is already taken part always passes.
Here is my script code
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function valemail()
{
var email = $('input#email').val();
var atpos=email.indexOf("@");
var dotpos=email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
document.getElementById("email").style.border="3px solid red";
document.getElementById('email_error').style.display = 'block';
document.getElementById('email_error').innerHTML = 'A valid email address is required';
} else {
if ($.trim(email) != '')
{
$.post('../ajax/registeremail.php', {email: email}, function(data)
{
if ($.trim(data) == 'That email address is already in use. If you have created an account,
<a href="../login.php">Login</a>')
{
document.getElementById("email").style.border="3px solid red";
document.getElementById('email_error').style.display = 'block';
$('div#email_error').text(data);
} else {
document.getElementById("email").style.border="3px solid #33FF33";
document.getElementById('email_error').style.display = 'none';
}
});
}
}}
</script>
My registeremail.php file works on its own and is:
<?php
include('../init.php');
//email validation
if (isset($_POST['email']) === true && empty($_POST['email']) === false) {
$email = $_POST['email'];
if (email_exists($email) === true) {
echo('That email address is already in use. If you have created an account, <a>Login</a>');
} else {
echo('Good');
}
?>
The actual text input and div code is
<input class="input" type="text" tabindex="2" placeholder="Email*" style="height:20px;" name="email"
id="email" onchange="valemail()">
<div id="email_error"></div>
Does anyone know why this is happening? I’m truly perplexed.
The problem is that what you echo in PHP is
and what you check for in JavaScript is
i.e. they are not the same …
I suggest you return a
1(true) or0(false) and then output the text using JavaScript .. Something likethen your JavaScript would be something like