1

Here is the code I wrote for ajax validation. I haven't yet created the submit button for the form. The problem is, I have to disable the submit button till all the fields are filled with appropriate information and validated in ajax way. This is just a sample with two fields. I've more than 20 fields like this.Please help me to do this. Thank you.

Form:

<p>
 <label for="cname">Name</label>
 <em>*</em><input id="cname" name="name" size="50" minlength="2"onkeyup="checkname()"/>
 <span id="target1"></span></p>
<p>
 <label for="fat">Father's Name</label>
 <em>*</em><input id="cfat" name="father" size="50" onkeyup="checkfather()" />
 <span id="target2"></span></p>

Javascript(ajax):

var ajax = create_ajax_object();
function checkname(){
    if(ajax){
        ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        document.getElementById("target1").innerHTML = ajax.responseText;
    }
        }
        ajax.open("POST", "ajval.php", true);
    var values = "name=" + encodeURIComponent(document.commentform.name.value);
    values = values + "&action=" + encodeURIComponent("check1");
    ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.send(values);
    }
    else{
        alert("Your browser doesnt support AJAX!");            
    }
}
function checkfather(){
    if(ajax){
        ajax.onreadystatechange = function(){
    if(ajax.readyState == 4 && ajax.status == 200){
        document.getElementById("target2").innerHTML = ajax.responseText;
    }
        }
        ajax.open("POST", "ajval.php", true);
    var values = "father=" + encodeURIComponent(document.commentform.father.value);
    values = values + "&action=" + encodeURIComponent("check2");
    ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.send(values);
    }
    else{
        alert("Your browser doesnt support AJAX!");            
    }
}

PHP:

<?php
$action = $_POST["action"];
switch($action)
{
case "check1":
    $name=$_POST["name"];
    if($name!="")
    echo '<img src="green-tick.png" height="20" width="20"/>';
    else
    echo'<span style="color:red;">Cannot be left blank</span>';
    break;
case "check2":
    $father=$_POST["father"];
    if($father!="")
    echo'<img src="green-tick.png" height="20" width="20"/>';
    else
    echo '<span style="color:red;">Cannot be left blank</span>';
    break;
?>
6
  • Is that PHP the complete validation for those two fields? If it is, there's absolutely no reason to use AJAX for client-side validation; JavaScript is more than capable of checking if a string is empty. Commented Mar 4, 2013 at 9:45
  • Hi there @AnthonyGrist I'm using a tabbed view for the form with many fields, so validating after clicking submit button will be disgusting. Commented Mar 4, 2013 at 9:49
  • I didn't say anything about validating after clicking a submit button. I'm talking about validating your inputs individually, using the same event handlers that you currently have, but not doing it with AJAX if you don't need to. If the only validation is that the entered value can't be an empty string then you don't need to use AJAX. Commented Mar 4, 2013 at 9:51
  • @AnthonyGrist you are correct, there is no need to use PHP to display ticks/error messages, Javascript can be used for this. Adding an XHR per field is slow and error prone way of doing this. Commented Mar 4, 2013 at 9:55
  • But, guys what you're saying is fully client side. But the bloody client wants server side validation as client side validation is unsafe. Commented Mar 4, 2013 at 10:05

2 Answers 2

1

You need to keep track of your valid fields. For each validation run a formIsValid method to check whether the form as a whole is valid and the submit button can be enabled.

I would suggest to run this separate from the actual ajax request as change events don't run quite reliably when using things such as copy paste or auto fill.

Since the ajax validation still requires a client side component it can be fooled and an invalid form can be sent. So you're not free from validating the complete form after submission anyway.

// you could have an object with validation expressions for each field
var fields = {
    name: /.+/,
    father: /.+/
}

// then once on load and after each successful ajax check run this method
function formIsValid () {
    var valid = true;

    for (var field in form.elements) {
        valid = fields[field.name].test(field.vlaue);
        if (!valid) {
            break;
        }
    }

    if all fields are valid the submit button will be enabled
    document.getElementById("submit").disabled = !valid;
}

The html for the button.

<!-- the disabled value is just for backwards compatibility -->
<input type="submit" id="submit" disabled="disabled" value="Send" />
Sign up to request clarification or add additional context in comments.

Comments

0

Your Javascript validation needs to return false on submit. In the HTML, you declare the form with an ID like so:

<form method="POST" action="confirm.php" id="theform">

You can do your ajax validation per field as usual onkeyup(), and set a boolean to true/false depending on whether it is valid or not.

And in the Javascript, Im using jQuery, you do the following:

$('#theform').submit(function() {
  valid = true;
  if() // check validation for 1st field
    valid == false;
  if() // check validation for 2st field
    valid == false;

  return valid;
}

If this function returns false, the form will not submit.

2 Comments

This doesn't really address the question at all, since he's asking about how to do AJAX validation of individual elements.
@AnthonyGrist He wants to disable form submit. This is how I would stop a form from submitting until all my validation is complete.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.