[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Using same rules for jQuery validation on server-side (PHP)

Posted on 2015-01-19
3
Medium Priority
?
101 Views
Last Modified: 2015-01-24
Any array parsing functions out there already built that allow me to specify rulesets which will output the client-side validation using jQuery.validate as well as loop through them on the server-side?
0
Comment
Question by:Mark
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 40558380
There are lots of array functions in PHP.  If you can show us some of the data and show us what you want to get out of it, I may be able to give you a tested and working example.  And don't overlook the various PHP frameworks -- all of them (WordPress, Joomla, CodeIgniter, Drupal, Laravel) have form validation routines.

A sample of server-side validation using plain-old PHP:
<?php // demo/form_highlight_errors.php
error_reporting(E_ALL);

/**
 * DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT, AND REMEMBER VALID INPUTS
 * CLIENT IS ASKED TO PUT IN A VALUE
 * IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
 * WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
 * WE TURN THE FORM BORDER RED
 * SEE http://www.w3schools.com/CSS/pr_class_visibility.asp
 */


// THESE STYLE ELEMENTS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = $error_xyz = $error_any = 'hidden';
$boxer_abc = $boxer_xyz              = 'black';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;


// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        // VALIDATION FAILED
        $error_abc = $error_any = 'visible';
        $boxer_abc = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        // VALIDATION FAILED
        $error_xyz = $error_any = 'visible';
        $boxer_xyz = 'red';

        // BECAUSE THIS FAILED VALIDATION, REMOVE IT FROM THE FORM
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OTHERWISE... OOPS - WE HAVE ERRORS AND MUST SHOW THE FORM AGAIN
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

0
 

Accepted Solution

by:
Mark earned 0 total points
ID: 40558744
I just created one myself ...

$rules = array(
	name => 						array( required => true, minlength=> 2 ),	
	phone=> 						array( required => true, validPhoneNumber => true ),
	email =>  						array(required =>  true, email =>  true )
);

$completerules = $rules;

foreach ($rules as $mastername => $mastervalue) {
    foreach ($mastervalue as $childname => $childvalue) { 
		if(startsWith($childname, 'SS_')) unset($rules[$mastername][$childname]); # Removes server side validation code embedded being presented to browser
	}
}

$x = json_encode($rules);

		var $validator = $('#listproperty').validate({
			rules: <?=$x?>,


And during server-side validation:
	foreach ($completerules as $mastername => $mastervalue) {

			if($mastervalue['SS_required']) $required = teval($mastervalue['SS_required'],$_POST);
			else $required = $mastervalue['required'];
			
			$minlength = $mastervalue['minlength'];
			$maxlength = $mastervalue['maxlength'];
			$value = $_POST[$mastername];
			$valuelen = strlen($value);
			
			if($required && !$value) $jsonoutput['fields'][$mastername] = 'Field Required';	
			else if($value && $minlength && $valuelen<$minlength) $jsonoutput['fields'][$mastername] = 'Invalid Value';
			else if($value && $maxlength && $valuelen>$maxlength) $jsonoutput['fields'][$mastername] = 'Invalid Value';else if($value && $mastervalue['digits'] && !$f->is_whole_number($value)) $jsonoutput['fields'][$mastername] = 'Digits Only';	
			else if($value && $mastervalue['email'] && !isemail($value)) $jsonoutput['fields'][$mastername] = 'A Valid Email is Required';	
			else if($value && $mastervalue['validPhoneNumber'] && !$f->is_valid_intl_tel($value)) $jsonoutput['fields'][$mastername] = 'A Valid Phone # is Required';
			else if($value && $mastervalue['currency'] && !$f->isCurrency($value)) $jsonoutput['fields'][$mastername] = 'A Valid Currency Amount Is Required';
			
	}

Open in new window

0
 

Author Closing Comment

by:Mark
ID: 40567968
Created one myself
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question