Solved

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

Posted on 2015-01-19
3
98 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 110

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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
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…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

739 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