Custom Data Validation

phpGrid automatically does data validation based on database data type such as a string cannot be used when the data type is integer and non-null field must have a value. It’s sufficient in most everyday use cases.

Client Side Validation

Starting version 5.5, users can use their own validation javascript function for more complex data edit rules. Use set_col_customrule() method is created for this purpose. Below is an example of three Javascript functions used for custom validation. You can even compare data among multiple columns. The Javascript functions in example is rather over simplified, but you get the picture. Once obtained the cell value, you can develop even more complex Javascript function to validation your data.

Server Side Validation

For server side data validation, in your javascript function, use jQuery.ajax to call your server side validation routine. An example of Ajax call can be found on Hyperlink to Call JavaScript Function example

Make sure that you play around with the live example after the code snippet!

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// validation (FORM and INLINE)
function price_validation1(value, colname) {
    if(value < 0){
       return [false,colname + " must be zero a positive integer."];
    }
    return [true, ""];
}

// validation (INLINE only). Note the technique to obtain a specific cell value
function price_validation2(value, colname) {
    var rowId = jQuery("#products").jqGrid('getGridParam','selrow');
    if(parseFloat(jQuery('#' + rowId + '_' + 'buyPrice').val()) >  parseFloat(jQuery('#' + rowId + '_' + 'MSRP').val()))
        return [false,"buyPrice must be equal or less than MSRP."];
    else
        return [true,""];
}

// validation (FORM only). Note the technique to obtain a specific cell value is different from INLINE edit.
function price_validation3(value, colname) {
    if(parseFloat(jQuery('#buyPrice').val()) >  parseFloat(jQuery('#MSRP').val()))
        return [false,"buyPrice must be equal or less than MSRP."];
    else
        return [true,""];
}

PHP

1
2
3
4
5
6
7
8
9
// Always include namespace and conf.php on TOP of the script.
use phpCtrl\C_DataGrid;
require_once("/path/to/conf.php");  

$dg = new C_DataGrid("SELECT * FROM products", "productCode", "products");
$dg->enable_edit('FORM');
$dg->set_col_customrule('quantityInStock', 'price_validation1');
$dg->set_col_customrule('buyPrice', 'price_validation3');
$dg->display();

See Live Example! (Try set quantityInStock to a negative number, and buyPrice < MSRP.)