Solved

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

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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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.

707 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