Form validation in combination with live username check

Last week I asked a question about live username availability. Paul Wilkins gave me some useful links which I have working now, But at the same time I still need to check if no fields are empty when the form is submitted and I am realy struggling to make this work. I have been looking for tutorials and/or examples of a combination of those two (Form Validation and Live email check) but couldn’t find any. So what I basically need is a function for three fields (name, username and password). None of the fields should be empty and the email field should be checked against values from the database!

Does anyone know of a good example or tutorial where those 2 functionalities are combined.

Thank you in advance!

Hi donboe,

I don’t know of any tutorials, but it shouldn’t be too hard to put this together ourselves.

Do you have an example form with the appropriate fields?

Hi Pullo. Thank you fot thr reaction :slight_smile: The fields involved are: Name, Profile name, username, password, city and Province. I realy hope you can help me out. This is driving me insane over the last couple of days. I have tried a lot of things but nothing was working as I had hoped for. Thank you in advance

Hi,

I meant can you provide the HTML for the form :slight_smile:

jQuery’s validation plugin makes it easy for such validation to occur. You can also add custom validation methods, so that the ajax request about checking the email can be done too.

The documentation at http://jqueryvalidation.org/documentation/ gives a good start on things.

Hi Pullo. This is the html for the form:


        <form method="post" action="" id="registratie_form" class="registratie" format="html" preservedata="yes">
          <div class="form_wrapper">
            <label for="naam" class="label">Naam:</label><input type="text" name="naam" id="naam" class="textfield">
          </div>
          <div class="form_wrapper">
            <label for="profiel" class="label">Profiel naam:</label><input name="gebruikersnaam" id="gebruikersnaam" type="text" class="textfield" >
          </div>
          <div class="form_wrapper">
            <label for="email" class="label">Email:</label><input name="username" id="username" type="text" class="textfield">
          </div>
          <div class="form_wrapper">
            <label for="wachtwoord" class="label">Wachtwoord:</label><input name="wachtwoord" id="wachtwoord" type="password" class="textfield">
          </div>
          <div class="form_wrapper">
            <label for="wachtwoord" class="label">Woonplaats:</label><input name="woonplaats" id="woonplaats" type="text" class="textfield" >
          </div>
     <div class="form_wrapper">
       <label class="label">Provincie:</label><select name="reg_provincie" class="selectfield">
                                              <option value="0">Maak een keus</option>
                                              <option value="1">Drente</option>
                                              <option value="2">Flevoland</option>
                                              <option value="3">Friesland</option>
                                              <option value="">...........</option>
                                              <option value="12">Zuidholland</option>
                                              </select>
      </div>
          <div class="form_wrapper">
            <label for="DOB" class="label">Geboorte datum:</label><input name="dag" id="dag" type="text" class="geboortefield" maxlength="2" placeholder="dd"><span></span><input name="maand" id="maand" type="text" class="geboortefield" maxlength="2" placeholder="mm"><span></span><input name="jaar" id="jaar" type="text" class="geboortefield" maxlength="4" placeholder="yyyy">
          </div>

          <div class="form_wrapper">
            <input name="submit" type="submit" value="verzenden" oclass="button">
          </div>
      <form>

@Paul. I have been looking into that. But I find it very complicated to comine the different things

Okay, well here’s a nice and simple example with the email field.


<label for="email" class="label">Email:</label><input name="email" id="email" type="text" class="textfield">

No change there.

The validate method needs jQuery, so you can use and external CDN to retrieve the scripts or you can host them yourself.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

A standard way to say that the email is required, is as follows:


$('form').validate({
    rules: {
        required: true,
        email: true
    }
});

We’re wanting something extra though. When someone has entered their email, we want to do a special check to see if that email already exists, We can use the PHP code to check if the email already exists:


$('form').validate({
    rules: {
        email: {
            required: true,
            email: true,
            remote: 'check-email.php'
        }
    }
});

Details about the remote check can be found at the remote method documentation page.

Do you have to specify required: true for the email field?

Wouldn’t it be better to put the required attribute in the input field so:

<input name="email" id="email" type="text" class="textfield" required>

That way if a user has JS turned off, but a HTML5 compliant browser, they will still be asked to enter a value into the field.

Yes, using the inline attribute is a better option when dealing with required, but I’ve found that it can get tricky to explain the details of which types of validation terms are accepted as inline tag attributes, when those details differ from the set documentation.

Given that though, the following is a preferred way to deal with things, where required is in the HTML code:


<label for="email" class="label">Email:</label><input name="email" id="email" type="text" class="textfield" required>


$('form').validate({
    rules: {
        email: {
            email: true,
            remote: 'check-email.php'
        }
    }
});

Hi Paul and Pullo. Thank you both for your input. Still this is the live email check, where I need the email check in combination with the normal validation. And that is the point where I get stucked. Ok I know I can use this rule:


rules: {
        email: {
            required: true,
            email: true,
            remote: 'check-email.php'
        }

\
for the other form fields as well but where do I apply the actual insert into the database when the validation is ok?

On the server when the client-side validation passes and the form submits, I would say.

Indeed - the form tag has an action attribute, which contains the PHP file that the form gets submitted to.

Do not just blindly assume that the form contents are going to be good though. There are several reasons for why scripting won’t end up checking the form, so always validate the form’s contents from the server side too.

The rule of thumb is to always validate from the server-side, and to use client-side validation where practical to provide a better user experience.

Hi Paul and Pullo. I am nearly there with the Validation. Thank you both for the input, but I am a bit struggling with the remote file (remote: ‘check-email.php’) This is what I have in the function:


rules: {
     email: {
         required: true,
         email: true,
         remote: "modules/site/check-email.php"
     }
}
messages: {
    email: {
        required: "Vul uw email adres in.",
        email: "Vul een geldig email adres in.",
        remote: jQuery.validator.format("{0} is al in gebruik.")
    }
}

And this is what I have in check-email.php:


if (!empty($_POST['email'])) {
    $email = $mysqli->real_escape_string($_POST['email']);
    $query = "SELECT email FROM profielen WHERE email = '{$email}' LIMIT 1;";
    $results = $mysqli->query($query);
    if($results->num_rows == 0) {
        echo "true";
    }
    else {
        echo "false";
    }
}
else {
    echo "false";
}

But no mather what email address I type in, I get the message that it is already in use. Even with email adresses that are not in the database. What am I doing wrong?

Thank you both in advance :tup:

For the purpose of testing, modify the PHP code to use $_GET instead, and test it manually with check-email.php?email=test@example.com

Can you get it to output true?

Hi Paul. Testing it that way it gives me true on a non existing email and false on a existing email. So what do I need to change?

Good, now use an ajax command to check a non-existing email. If you get “true” back as an answer, how long is that string of data? If JavaScript says that it’s longer than 4 characters, then some PHP work needs to be done.

[ed: looking at the documentation takes us on a different track, see below]

I also see from the documentation that a GET request is made to the server when the check is made. That might go a long way towards helping to solve things.

http://jqueryvalidation.org/remote-method/

I also see in the documentation that “The response is evaluated as JSON and must be true for valid elements”, so it looks like the output from the PHP file needs to be as JSON data:


{email: "true"}

The easiest way to do this properly is by using http://www.php.net//manual/en/function.json-encode.php

Hi Paul. :frowning: Sorry for maybe a stupid question But what kind of ajax command and where and how? I know a little bit of java but this is completely new to me

Edit: Just to test it I left it on GET and now it is working it seems

Here is an example taken from jquery’s documentation page at http://api.jquery.com/jquery.get/


$.get( "test.cgi", { name: "John", time: "2pm" } )
  .done(function( data ) {
    alert( "Data Loaded: " + data );
  });

Modifying that for your particular situation is child’s play, and gives:


$.get( "check-email.php", { email: "test@example.com" } )
  .done(function( data ) {
    alert( "Data Loaded: " + data );
  });