tags:

views:

841

answers:

5

Here's the situation:

I'm using jquery.validate.js to validate my forms, but I need to add a server-side validation layer. jQuery Validate uses class names within form-elements to determine what it should do -- I want to fetch those class names into PHP so that I can perform the same validations on the server-side.

I'm hoping to do something like this:

foreach($_POST as $key=>$value) {
     $class=array(...// get this #key element class name list with jQuery
     $error=...// based on the class names, perform specific PHP validations
     if($error=="")
         return true;
     else
         return false;
}

Question is, can I do this? Can I fetch element class names w/ jQuery and pass them to PHP?

A: 

serializeArray will convert your form data to JSON:

var json = $('#formid').serializeArray();

Typically you can send the entire JSON string to the server which can take it from there.

aleemb
+2  A: 

You could get jQuery to send the class names along with the form - HOWEVER this leads to serious security issues. Seeing as everything posted to your server is really done by your users browsers, your users will have the ability to then change your validation rules and as such bypass them, and that would make your entire purpose here useless. I would instead suggest the following.

Make a function in php to take in the name of a form element and return appropriate class names. When generating each form element for the form, call this function to get the class names (and then applying the jQuery validation). When you read your form in your PHP code - use the same function to get the class names and then you know which validation rules to apply in your server side php code.

Hope it made sense.

kastermester
How can I call a PHP function from jQuery?
rebellion
@Ronny-André Bendiksen - this a completely different topic and would probably serve better with a new question. Short version would be to have a regular .php page where that function is getting invoked - and then utilize the jQuery.ajax method (see jQuery manual for more indepth explanation of this)
kastermester
+1  A: 

client-side:

function validate()
{
    var params = {
       var1: {key:$('#field1').get(0).className, value:$('#field1').get(0).value},
       var2: {key:$('#field2').get(0).className, value:$('#field2').get(0).value},    
       ...
    }
    $.post('http://host/validate_script.php', params, onValidate);
}
function onValidate(data)
{
    alert(data);
}

hope this will help... sure it's a simple way and you can do it more formalized.

Jet
+1  A: 

Never trust the client(browser)!

You should never allow anything on the client to dictate to the server how to test the validity of posted information.

This is a very bad idea.

Spot
A: