Disable form submit on external validation check script

I want to disable a form submit if a div has a message contained within it.

I have a form that checks an external source for some validation. If the validation checks are not met, then a warning message is displayed in a div (dispemail).

I'd like to disable my submit button if a message is displayed in this div.

My form is:
<form action='formprocessor.php' method='post' id='member-add'>
<table cellpadding='5px' cellspacing='5' >
<tr><td>Email</td></tr>
<tr><td><input type='text' name='email' id='email' value=''/><div id='dispemail'></div></td></tr>
<tr><td><input type='submit' value='Submit' style='margin-top:20px; margin-bottom:40px' id='submit'/></td></tr>
</table>
</form>

Open in new window


The Javsacript to call the ajax validation script:
<script type="text/javascript">
$(document).ready(function(){
$("#email").blur(function() {
var email = $('#email').val();
if(email==="")
{
$("#dispemail").html("");
}
else
{
$.ajax({
type: "POST",
url: "check-email.php",
data: "email="+ email,
success: function(html){
$("#dispemail").html(html);
}
});
return false;
}
});
});
</script>

Open in new window


The validation code:
<?php

if(isset($_POST['email'])){
$email=(($_POST['email']));

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.xxxxx.com",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_POSTFIELDS => "{}",
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}


$responsetext=json_decode($response, true);

if ($responsetext['result']=='undeliverable'){
$message = $responsetext['email']." is not a valid email - ".$responsetext['reason'];
echo "<p class='error'>$message</p>";

}
else {
$message = $responsetext['email']." is a valid email";
echo "<p>$message</p>";
}



}

?>

Open in new window

rwlloyd71Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
I think the easiest way to do this is to pass a boolean back from your validation script along with the message. Set the boolean to true/false based on the vaidation result and then check that in your success handler. So your script would look something like this:

if ($responsetext['result']=='undeliverable'){
    $message = $responsetext['email']." is not a valid email - ".$responsetext['reason'];
    echo json_encode([
        'valid' => false,
        'message => "<p class='error'>$message</p>";
    ]);
}
else {
    $message = $responsetext['email']." is a valid email";
    echo json_encode([
        'valid' => true,
        'message => "<p>$message</p>";
    ]);
}

Open in new window

Then in your success handler, you would do:

success: function(response){
    $("#dispemail").html(response.message);
    $('#submit').prop('disabled', response.valid);
}

Open in new window

0
lenamtlCommented:
Disabling a button won't prevent form submit, enabling a disabled button is very easy to do from the front side (chrome Inspect)
To prevent form submit you have to add server side validation (PHP).

for client side Javascript
Just add
disabled attribute

Open in new window

to your submit button if you want your button disabled by default

then if the form meet the criteria
$("#submit").removeAttr("disabled");

Open in new window


or put back disabled
$("#submit").attr("disabled", "disabled");

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
Some comments before offering a solution
1. Use of tables for layout - this is not considered good practice - just something to consider
2. I would be cautious of using a validation on email that attempts to validate by sending an email. Greylisting is an anti spam mechanism whereby the server temporarily rejcets incoming mail on the premise a valid sender will retry. This could (in your case) result in an email being rejected when it is valid
My recommendation is to validate the email on the server to see if it is a correctly formed email and then send an activation email. This is the standard way of doing things.

Here is simple example of how to do this
HTML (I have used your HTML but would recommend moving away from tables)
<form action="formprocessor.php" method="post" id="member-add">
  <table cellpadding="5px" cellspacing="5" >
	<tr><td>Email</td></tr>
	<tr><td><input type="text" name="email" id="email" value=""/><div id="dispemail"></div></td></tr>
	<tr><td><input type="submit" value="Submit" style="margin-top:20px; margin-bottom:40px" id="submit"/></td></tr>
  </table>
</form>

Open in new window

The JQuery
<script>
$(function() {
  var formValid = true;
  $('#email').change(function(e) {
    var email = this.value;
    $('#dispemail').html('');

    $.post('t3379.validate.php', {email: email}, function(resp) {
      if (!resp) {
        $('#dispemail').html(email + ' is not a valid email address');
      }

      formValid = resp;
    },'JSON');
  });
  
  $('form').submit(function(e) {
    if(!formValid) {
      e.preventDefault();
      alert('Form is not valid');
    }
  });
});
</script>

Open in new window

The PHP Code
This is for demonstration only - other functionality may be added such as a lookup to see if the email has been used etc.
<?php
$email = isset($_POST['email']) ? $_POST['email'] : false;

$resp = ($email && filter_var($email, FILTER_VALIDATE_EMAIL));
die(json_encode($resp));

Open in new window


Working sample here
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

rwlloyd71Author Commented:
Thank you for all your comments.

A couple of points:

Chris, you missed a couple of ' after the json 'message' response and added a ";" which caused some confusion. The valid value is returned,  but it does not seem to disable the submit button. Do I need to add anything to the submit button?

Lenamtl, thanks for the input, but did not really see how to use the advice.

Julian, valid point about the tables, but I am just following the style of the website. The validation is not just to check against the email format, but uses a 3rd party service to check if the domain name exists, the account is valid etc. Our main problem is typos in email addresses.

With regard to your code, I can I send you something privately that might make a bit more sense?
0
lenamtlCommented:
Well you have a form I guess the submit button should be disabled at this point so you can add disabled attribution to that button.
Then you have Javascript validation with cases
so when you are checking what it need to enable the button you can remove the disabled attribution,
if for a reason it's not meeting the requirement you can add the disabled attribution back.

When the button is submitted you need server side validation as the Javascript validation is not secure and you cannot rely on it.
So let say you use PHP then you need to check with PHP every input result then if it meet the request send the data to DB or elsewhere
if not display a message so user can change the data in the form...

Hope it is more clear
0
Chris StanyonWebDevCommented:
Sorry about the typos.

You shouldn't need to add anything to the submit button. All it's doing is adding the disabled property to the #submit button, so as long as you have an ID of submit on it, you should be fine.
0
Julian HansenCommented:
The code I posted can still be used if you want to do a domain check. The principle remains the same - all that you are adding is a CUrl request in the PHP code to return a true / false value - the client side code remains unchanged.
0
Julian HansenCommented:
to check if the domain name exists, the account is valid etc
You can check if the domain exists but I don't think you can rely on a validity check on the email. It would be a great way for spammers to build up lists of valid email addresses if you could.

My point regarding the validation is that in my experience there is a chance that the service will report an invalid email when in fact it is valid - simply because SPAM firewalls are designed to protect against exactly what you are trying to do.
0
Chris StanyonWebDevCommented:
@Julian - a service like Mailgun is designed to specifically check the validity of an email address, and you'd do it by sending a curl request to their API. Dont know how their internals work, but I'm guessing (hoping) it's not just by trying to send an email. Doesn't look like the OP is using Mailgun, but maybe a similar service ??
0
rwlloyd71Author Commented:
I am using kickbox.io, same as mailgun I think. It is very good.
0
Julian HansenCommented:
I was under the impression that Mailgun & co were more for keeping your mailing list sanitised than for real time email verification. I would be interested to see the failure rate on that - and how you would handle a failure - do you reject the email totally or give the person a chance to validate in another way.

What is the cost of a false negative?
0
rwlloyd71Author Commented:
Difficult question to answer, but it seems ok so far.

It is good for picking up typos for gmall.com or gmail.co.uk for instance. It validates the existence of some ISP mailboxes, including gmail, so xxx@gmail.com would fail, but real.address@gmail.com would pass. By using it we have cut down a huge number of problem accounts.

At the moment I am just displaying warning messages if the email is rejected, but the users just ignore them and accept the email anyway! Hence the reason for this belt and braces code.

What I will probably end up doing is requesting a checkbox to be ticked if the email is rejected, which will re-able the submit button in case of false positives.

Which they will no doubt do anyway! Can't win either way!
0
Chris StanyonWebDevCommented:
There is a way you could maybe handle this, depending on your needs. If the email address is validated through the API, then proceed as normal.

If the validation comes back as 'failed', then push a message to your user saying 'Automatic Validation Failed. Please check your email'. You could then send a genuine email validation. You actually send an email to the address with a link to your own validate script (containing a unique ID Hash). The user then has to click that link to validate their address - effectively offering a 2-step validation.

I don't know what kind of responses kickbox gives you (valid / invalid / unknown etc.) so you would need to decide on the logic yourself. The 2-step process would only kick in if needed, and give genuine users the opportunity to verify manually.
0
Julian HansenCommented:
I would do the validation email anyway - I don't know what your use case is but you would want to avoid the case where

a) User mistypes email address but it still passes validation
b) User inputs somebody else's email

However, I get the feeling we are diverting from the original question which was about how to disable your form until the Email was validated.

Code for doing this has been provided.
0
rwlloyd71Author Commented:
Guys, thanks for all the input.

I need to think through all the comments and come up with some business logic that will help define what I need.

I'm going to close the question and give you both credit for now

Thanks
0
Chris StanyonWebDevCommented:
So my comments didn't help ?? Fair enough !
0
Julian HansenCommented:
@rwlloyd71, I suspect you left Chris off the merit list by accident - can I reopen so you can regrade?
0
rwlloyd71Author Commented:
Apologies if I didn't get that right. I find this bit really confusing. Let me know what I need to do.

You both have been very. Helpful.
0
Chris StanyonWebDevCommented:
** Sigh ** The accepted solution does not address the question, and technically incorrect! You should always use prop and not attr
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.