Para validar cualquier campo presente en el colModel del
Jqgrid con una función personalizada es bastante sencillo:
Pasó 1 Crea la función
Usemos una función que valide si la persona escribió el
valor o si escribió letras en vez de números:
(Importante esta función debes colocarla antes del cuerpo
del Jqgrid, fijate en el código completo del ejemplo más abajo)
function
fol(value, colname) {
if(!isNaN(value))
{
if(parseFloat(value) == 0 )
{
return[false,"No
puede Grabar el Valor 0"];
} else {
return[true,
""];
}
} else {
return [false, "Debe Escribir solo numeros"];
}
};
Pasó 2:
Luego en la línea correspondiente dentro del jqgrid llamas
la función:
Importante los parámetros de editrules debe estar así
editrules:{custom:true,
number:true, custom_func:fol}
{name:
'Cantidad', index: 'Cantidad', width: 80, align: 'left',editable:
true,editrules:{custom:true, number:true, custom_func:fol},formatter:
'number',edittype:'text'},
CODIGO COMPLETO
<!--
<link rel="stylesheet" type="text/css" href="css/estilo.css">
<link rel="stylesheet" type="text/css" media="screen" href="text/css/ui-lightness/jquery-ui-1.10.1.custom.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="text/js/jquery-ui-1.10.1.custom.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script language="javascript" src="scripts/sisminalve.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript" src="scripts/validar.js"></script>
<script type="text/javascript" src="text/js/jquery.ui.datepicker-es.js"></script>
<?php
extract($_POST);
extract($_GET);
include('funciones/Conectar.php');//Conexion a la Base de datos
include('funciones/FuncionesListBox.php');
include('funciones/globales.php');
include('funciones/librerias.php');
?>
<script>
function formafecha(fecha)
{
Anio =fecha.substr(0,4);
mes=fecha.substr(5,2);
dia=fecha.substr(8,2);
fecha=dia+"/"+mes+"/"+Anio;
return (fecha);
}
$(function() {
$( "#fechaR" ).datepicker();
});
</script>
<script type="text/javascript">
$(function(){
var identificador_rubro=$('#Renglon_Oculto').val();
var Identifica_accion =<?php echo $_GET['rp'];?>;
var selICol; //iCol of selected cell
var selIRow; //iRow of selected cell
$("#enlace").click(function() {
location.href = this.href; // ir al link
});
$.jgrid.formatter.integer.thousandsSeparator = ',';
$.jgrid.formatter.number.thousandsSeparator = '.';
$.jgrid.formatter.number.decimalSeparator = ',';
$.jgrid.formatter.number.decimalPlaces = 2;
$.jgrid.formatter.currency.thousandsSeparator = '.';
$.jgrid.formatter.currency.decimalSeparator = ',';
$.jgrid.formatter.currency.decimalPlaces = 2;
var darticulo = (function () {
var list = null;
$.ajax({
async: false,
global: false,
url: 'Articulo.php',
dataType: 'json',
success: function (data) {
list = data;
}
});
return list;
})();
var drubro = (function () {
var list = null;
$.ajax({
async: false,
global: false,
url: 'Rubro.php',
dataType: 'json',
success: function (data) {
list = data;
}
});
return list;
})();
function fol(value, colname) {
if(!isNaN(value))
{
if(parseFloat(value) == 0 )
{
return[false,"No puede Grabar el Valor 0"];
} else {
return[true, ""];
}
} else {
return [false, "Debe Escribir solo numeros"];
}
};
$("#grps").jqGrid({
url:'Carga_Datos.php?filtro='+<?php echo $_GET['rp'];?>,
datatype: 'json',
mtype: 'GET',
colNames: ['Rubro','Articulo','Lote','Cantidad','Peso_Total','Fecha_Vencimiento','Observaciones'],
colModel: [
{ name: 'Rubro', index: 'Rubro', width: 80 ,align: 'left',editable: true,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: drubro,dataEvents: [{type: 'change',
fn: function(e)
{
// RUTINA PARA CREAR LA RELACION EN LOS COMBOS EL CODIGO MEDIDA_FILTRO.PHP SE ENCUENTRA EN LA PARTE FINAL DE LA PAGINA.
$("#grps").setColProp("Articulo", {editoptions: { value: darticulo}});
var v = parseInt($(e.target).val(), 10);
$.ajax({
url: "Articulo_Filtrado.php?Id="+v,
dataType: "html",
success: function(data)
{
if ($(e.target).is(".FormElement"))
{
var form = $(e.target).closest("form.FormGrid");
$("select#Articulo.FormElement", form[0]).html(data);
}else{
// inline editing
var row = $(e.target).closest("tr.jqgrow");
var rowId = row.attr("id");
$("select#" + rowId + "_Articulo", row[0]).html(data);
}// cierra el if
}// cierra funcion de comprobacion de exito
}); // cierra el ajax
}//cierra funcion e
}]//cierra evento change
}// cierra editoptions
}, // cierra la linea de sistema
{name: 'Articulo', index: 'Articulo', width: 80, align: 'left',editable: true,editrules:{required:true},formatter:'select',edittype:"select",editoptions:{value: darticulo},sortable: true},
{name: 'Lote', index: 'Lote', width: 80, align: 'left',editable: true,editrules:{required:true},formatter:'text',edittype:"text"},
{name: 'Cantidad', index: 'Cantidad', width: 80, align: 'left',editable: true,editrules:{custom:true, number:true, custom_func:fol},formatter: 'number',edittype:'text'},
{name: 'Peso_Total', index: 'Peso_Total', width: 80, align: 'left',editable: false,editrules:{custom:true, number:true, custom_func:fol},formatter: 'number',edittype:'text',editoptions:{dataEvents: [
{
type: 'keypress',
fn: function(e) {
var key = e.charCode || e.keyCode; // to support all browsers
if (key == 13){setTimeout("jQuery('#grps').editCell(" + selIRow + " + 1, " + selICol + ", true);", 100);}
if((key < 48 || key > 57) && key !== 46 && key !== 44 && key !== 8 && key !== 37 && key !== 39){ return false;}
}// cierra la funcion e
}// cierra el control del keypress
]
}// cierra editoptions
}, // cierra la linea de sistema
{name: 'Fecha_Vencimiento', index: 'Fecha_Vencimiento', width: 50, align: 'center', editable: true,editrules:{required:true},formatter: 'text', editoptions:{size:20,
dataInit:function(el){
$(el).datepicker({dateFormat:'dd/mm/yy'});
},
defaultValue: function(){
var currentTime = new Date();
var month = parseInt(currentTime.getMonth() + 1);
month = month <= 9 ? "0"+month : month;
var day = currentTime.getDate();
day = day <= 9 ? "0"+day : day;
var year = currentTime.getFullYear();
return day+"/"+month + "/"+year;
}
}
},
{name: 'Observaciones', index: 'Observaciones', width: 80, align: 'left',editable: true,editrules:{required:true},formatter:'text',edittype:"text"},
],
rownumbers:true,
pager: '#pgrps',
rowNum:10,
rowList:[10,25,50,100],
autowidth: true,
viewrecords: true,
width: "98%",
height: "100%",
editurl: "someurl.php",
caption: 'Carga Asientos Contables',
footerrow: true,
//cellEdit: true,
//cellurl:"otro.php",
afterInsertRow:function(rowid,rowdata,rowelem) {
var ret = jQuery("#grps").jqGrid('getRowData', rowid);
$.getJSON('Busca_Kilos.php',{Codigo:ret.Articulo},Busca_Texto);
function Busca_Texto(datos)
{
var z =(parseInt(datos)*ret.Cantidad);
$("#grps").jqGrid('setCell',rowid,'Peso_Total', z);
}
},
});
jQuery("#grps").jqGrid('navGrid','#pgrps',{}, //options
{
afterSubmit:processAddEdit,
closeAfterAdd: true,
closeAfterEdit: true,
reloadAfterSubmit:false,
recreateForm:true
},
//{reloadAfterSubmit:false,closeAfterEdit:true,recreateForm:true},// edit
{reloadAfterSubmit:false,closeAfterAdd:true,recreateForm:true}, // add options
{reloadAfterSubmit:false}, // del options
{multipleSearch:true,closeAfterSearch: true, closeOnEscape: true}
);
function processAddEdit(response, postdata) {
$.getJSON('Busca_Kilos.php',{Codigo:postdata.Articulo},Busca_Texto);
function Busca_Texto(datos)
{
var z =(parseInt(datos)*postdata.Cantidad);
$("#grps").jqGrid('setCell',postdata.id,'Peso_Total', z);
}
return [true,"",];
}
$("#bedata").click(function()
{
// CODIGO MUY IMPORTANTE SIN EL CUAL NO SE GRABARAN TODAS LAS FILAS DEL GRID
var total_registros =jQuery("#grps").jqGrid('getGridParam', 'records');// lee el numero total de filas a recorrer
jQuery("#grps").setGridParam({ rowNum: total_registros }).trigger('reloadGrid');// cambia el numero de filas por defecto que tiene el grid
//jQuery("#grps").jqGrid('excelExport',{tag:"pdf","url":"querygrid.php"});
if(!confirm(" Esta seguro de Grabar los Registros?"))
{
return false;
}else{
var busca_error =0;
var mensaje ="";
var Identifica_Usuario=$('#Id_Usuario').val();
var proveedor=$('#Id_Proveedor option:selected').val();
var Almacen = $('#Id_Almacen option:selected').val();
var Fecha = $('#fechaR').val();
var Factura = $("#Factura_Nota").val();
var cantidad = $("#grps tbody").find("tr").length;
if (cantidad==1){busca_error=2;mensaje="No Puede Grabar Registros en blanco";}
if (proveedor==""){busca_error=1;mensaje="Proveedor";}
if (Almacen==""){busca_error=1;mensaje="Almacen";}
if (Fecha==""){busca_error=1;mensaje="Fecha";}
if ($("#Factura_Nota").val()==""){busca_error=1;mensaje="Factura Nota Entrega";}
if(busca_error==0)
{
var z=0;
var texto ="";
var columns = new Array ();
var lista = jQuery("#grps").getDataIDs();
for(i=0;i<lista.length;i++)
{
rowData=jQuery("#grps").getRowData(lista[i]);
columns[z]=rowData.Articulo+';'+rowData.Lote+';'+parseInt(rowData.Peso_Total)+';'+parseInt(rowData.Cantidad)+';'+rowData.Fecha_Vencimiento+';'+rowData.Observaciones;
z++;
}// cierra el for
var jObject={};
for(i in columns)
{
jObject[i] = columns[i];
}
$.post("Graba.php",{jObject: jObject,proveedor:proveedor,Almacen:Almacen,Fecha:Fecha,Factura:Factura,Identifica_Usuario:Identifica_Usuario},function(result)
{
alert(result);
$("#enlace").click();
});
// return false;
}else{
if (busca_error==1){alert('Ingrese un Valor para el Campo '+mensaje);}
if (busca_error==2){alert(mensaje);}
}
} // cierra el confirm
}); // cierra la funcion clic
});
</script>
--!>