Solved

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

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

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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
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…
The viewer will learn how to count occurrences of each item in an array.

809 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