Solved

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

Posted on 2015-01-19
3
92 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
  • 2
3 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Comment Utility
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
Comment Utility
Created one myself
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now