YUI Datatable – Custom Validator Example

This is the validator I am using to insure that a height (or float) was entered (5’10″, 5′ 10″, 5.10 5 10), and that text (tall, short) was not entered and covert a valid non-float value entered (5’10″, 5′ 10″, 5 10) to a float (5.10), which is how I want to store the value in the database for this example.

Now that we have a custom validator created, it would be helpful to know where to call it from. A validator is an object parameter to the object that is sent to a textboxCellEditor.

The textboxCellEditor is an object parameter to the object that defines the column, in the array of objects that is sent to the datatable constructor.

STWPT.validateHeight = function (oData)
{
    var pattern; // regexp pattern holder
 
    // heightFormat is expected to be a decimal number for height
 
    // add a space if none was provided (5'10")
    // 5'10" -> 5' 10 - note the trailing non-digit characters are dropped
    pattern = /'(\d+)/g
    if (pattern.test(oData)) { oData = oData.replace(pattern, " $1"); }
 
    // turn a space into a decimal - 5 10, 5' 10" -> 5.10, 5' 10"
    pattern = / /g;
    if (pattern.test(oData)) { oData = oData.replace(pattern, '.'); }
 
    // remove all single and double quotes - 5' 10", 5'.10" -> 5.10
    pattern = /["']/g
    if (pattern.test(oData)) { oData = oData.replace(pattern, ''); }
 
    // enforce x.0x format - 5' 1" -> 5' 01" -> 5.01
    pattern = /\.([1-9])$/
    if (pattern.test(oData)) { oData = oData.replace(pattern, '.0$1')};
 
    // at this point we should have a float, which should eval > 0
 
    if (oData > 0) { return oData; }
 
    // validation only succeeds if a value is returned
}

The following is a snippet out of a larger script that shows just the pieces that connect the datatable creation to the custom validator shown above.

var heightEditor = new YAHOO.widget.TextboxCellEditor({
    disableBtns: false,
    asyncSubmitter: submitter,
    validator: STWPT.validateHeight
});
 
var myColumnDefs = [{
    key: 'height',
    label: 'Height',
    sortable: true,
    resizeable: true,
    editor: heightEditor,
    formatter: STWPT.formatHeight
}];
 
var myDataTable = new YAHOO.widget.DataTable('athletes-datatable', myColumnDefs, myDataSource);

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">