Client and server side validation

Hi,

I would like to ask some questions regarding server side and client side validation, I know that server side validation is a must and client side validation is optional so the user can have a better experience (no page load, quick response etc).

I’ve got a registration form and at the moment I’m only performing a server side validation.
So the form sends the request to a file called processor.php this file perform all the validation and returns the error if validation failed.
At the moment I’m usign sessions to store the error and redirect to the registration form so I can show the error message to the user.
Now the question is: if I also want to implement client side validation, fo example using the jquery validator plugin, has the client side validation priority over the server side validation? I suppose also it doesn’t make sense using ajax call in this case is it correct?

Many thanks for your help

Yes, the client side will have ‘priority’ over the server side, simply because of execution time.

User fills out form.
User pushes submit button.
Client side Validation Occurs. If error detected, stop here, display error.
Form data submitted to server.
Server side validation occurs.
Server returns results.

Hi @m_hutley many thanks for your help. I’ve got another question. What about the success message I can use Ajax and show the success message from processor.php using json stored in processor.php but I believe in the processor.php I still need to keep the success message stored in the session otherwise if JavaScript is not enabled in the user browser then Ajax doesn’t work is it correct?

Well AJAX stands for Asynchronous Javascript And XML… if Javascript is not enabled, then yes, AJAX will not work.

You can however fairly easily flow around that; essentially have your form try to submit via AJAX, and interrupt the default submit action. If Javascript is disabled, that wont happen, and the regular submit pattern will happen.

That is great so in the processor.php I suppose I still need to store the success message into a session in case JavaScript is disabled and also store the same message into json array for Ajax call as I don’t know any php method to pass messages between pages using json

Well the PHP would generate the HTML response. A form error would not need to persist between pageloads, so i’m not sure why you need a session.

Well it is because i’m Keeping the php logic separated from the view so i’ve Set up the form action from registration.php to process.php
If I print the error without a session it will be shown in the processor.php page

Is processor.php a “page” or is it a “processor”?

A processor script should be able to spit out any HTML template/page you want ask it to.

Hi @SamA74 the processor.php is a page

OK, I’m not sure how your logic currently runs, but a typical form processor I might use would follow something like this this (in simplified pseudo/skeletal code)

<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){ // A form submission
		
     // process the validation...

     if($validForm){   // Everything passes validation
         header("location: /success.php" );  // Redirect for success
         exit; // Stop running
     }
}
$htmlContent = 'thehtmlform.php' ; // No redirect, just set the HTML template to the form

So if everything works good, you get redirected to the success page.
If validation fails, or you are visiting the form for the first time, you see the form.

Note the processor is a processor, a script the runs logic, the page it displays can be any html page you chose, or any of a number of different pages depending on the outcome of the logic.
So for example instead of the redirect to the success page, I could just set the html to success.php in that if block. (though I don’t to avoid refresh resubmits).

1 Like

Hi @SamA74 thanks for your answer, this is my code for rregistration page with the form

 <?php km_registration_error_notice(); ?>

              <form action="<?php echo KM_BASE_URL.'/km-controllers/km-ctrl-register.php' ?>" method="POST" autocomplete="off">
                
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label class="control-label">Nome
                      <span class="required"> * </span>
                    </label>
                    <input type="text" name="userName" id="userName" class="form-control" placeholder="Inserici il tuo nome" maxlength="30" >
                  </div>
                  <div class="form-group col-md-6">
                    <label class="control-label">Cognome
                      <span class="required"> * </span>
                    </label>
                    <input type="text" name="userSurname" id="userSurname" class="form-control" placeholder="Inserisci il tuo cognome" maxlength="30" >
                  </div>
                </div>

                <div class="form-row">
                  <div class="form-group col-md-12">
                     <label class="control-label">Indirizzo email
                      <span class="required"> * </span>
                    </label>
                     <input type="text" name="userEmail" id="userEmail" class="form-control" placeholder="Inserisci la tua email" maxlength="320" >
                  </div>
                </div>

                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label class="control-label">Nome utente
                      <span class="required"> * </span>
                    </label>
                     <input type="text" name="userUsername" id="userUsername" class="form-control" placeholder="Inserisci il tuo nome utente" maxlength="30" >
                  </div>
                  <div class="form-group col-md-6">
                    <label class="control-label">Password
                      <span class="required"> * </span>
                    </label>
                     <input type="password" name="userPassword" id="userPassword" class="form-control" placeholder="Inserisci la tua password" maxlength="50" >
                  </div>
                </div>

                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label class="control-label">Codice utente
                      <span class="required"> * </span>
                    </label>
                     <input type="text" name="userCode" id="userCode" class="form-control" placeholder="Inserisci il tuo codice utente" maxlength="30" >
                  </div>
                </div>

                <input type="hidden" name="registerToken" value="<?php echo km_generate_registration_token(); ?>">
           
                <div class="form-group mx-auto">
                    <button type="submit" name="registerSubmit" class="btn btn-primary">Registra profilo utente</button>
                </div>

              </form>

This is km-ctrl-register.php file I’ve just posted part of it as an example

if(isset($_POST['registerSubmit'])) {

    // Validate form token against session to prevent cross site request forgery
    if(km_validate_registration_token($_POST['registerToken'])) {

        $user_first = trim(filter_var($_POST['userName'], FILTER_SANITIZE_STRING));
        $user_last = trim(filter_var($_POST['userSurname'], FILTER_SANITIZE_STRING));
        $user_email = trim(filter_var($_POST['userEmail'], FILTER_SANITIZE_EMAIL));
        $user_username = trim($_POST['userUsername']);
        $user_password = trim($_POST['userPassword']);
        $user_code = trim(filter_var($_POST['userCode'], FILTER_SANITIZE_STRING));

            // Validate form fields if they are empty
            if(empty($km_user_first)) {

                // Error message if first name field is empty
                $_SESSION['km_error_message'] = 'insert name!';
                // Redirect to registration form
                header('Location: '.KM_BASE_URL.'/km-views/km-register.php');
                exit();
            }else{

               // success message
                $_SESSION['km_success_message'] = ok fine';
                // Redirect to registration form
                header('Location: '.KM_BASE_URL.'/km-views/km-register.php');
                exit();


            }

      }

  }

As you have it, because you redirect in both instances, success and failure, you would need a session.

I guess @m_hutley presumes you use a method similar to my example, where the controller that shows the form, is also the form’s action and contains the validation processing (or calls some such method). So effectively you stay with the form until you have a valid submit and only get forwarded once you pass validation. This way you can build an array of validation errors to display in the form which you have access to without any session.

Note, what I describe does not go against this. The processor is not the html form page, but it does include it by some means if/when required.

Yes you are right I quite like your solution it seems to be very close to a MVC solution that I’m looking for :slight_smile:
I’ll play with it a little bit, many thanks for now :wink:

Hi @SamA74 I’m working on your suggestion. I was thinking this line of code should it be a require?

It could well be if you wish. It just depends on your particular set up.
Setting it as a variable like this could just be to pass on to a common entry point type script which does the include/require, so it does end up as one. But you can work it as you like.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.