Tuesday 11 August 2009

Tracking with dcsMultiTrack invalid fields on client side

dcsMultiTrack - is 3rd compoment. Instead of dcsMultiTrack you can use your own tracking tool or for example google analytics.

Sometimes you can find yourself in situation when you want to track if some of the fields on your form is not valid. Track some value when it does not goes through clientside validation. In this situation you need to somehow hook up on or before validation it self will be executed. In my sample I use custom javascript function which executes validation on form fields and based on their validity reporting status of the form.

1) set custom attribute on the field you want to track. For example on textbox with username you can set up attribute DSCError with value "UN".
<asp:textbox id="username" runat="server" DSCError="UN" />

2) place validation control by own choice (regular, required, custom ...) and ensure that clientside validation is turned on.

3) The button used for submit need to have onclick clientside event with own function used for validation. Custom validation function should contain one parameter ValidationGroup (useful for avoid validation of other validationgroups).
For example onclick="PreValidation('MyValidationGroup');"

4) Custom validation function. Function should consume ValidationGroup name but it is not required. If you does not provide it  (PreValidation('') or PreValidation() ) function will validate all fields with validators.

function PreValidation(valGroupName) {
var errorsToReport = "";

for (i = 0; i < Page_Validators.length; i++) {
var val = Page_Validators[i];
// in case there is no value for valGroupName validate all validators
if (typeof (valGroupName) == 'undefined' || valGroupName == '' ||
val.validationGroup == valGroupName)
{
var cntrToValidate = $get(val.controltovalidate);
if (cntrToValidate != null) {
var DSCError = cntrToValidate.attributes["DCSError"];
if (DSCError != null) {
ValidatorValidate(val, val.validationGroup, null);
if (val.isvalid == false) {
errorsToReport += (errorsToReport.length > 1 ? "," : "");
errorsToReport += DSCError.value;
}
}
}
}
}
if (errorsToReport.length > 0) {
dcsMultiTrack("DCS.dcsuri", "/your_page_name", "DCSext.ErrorFields", errorsToReport);
}
}


How does it works? Well firstly we need to go through all validators on the page, they are present in Page_Validators collection. Then check out whether actuall validator could be evaluated or not. If so store field you tracking into variable cntrToValidate. Check present of custom attribute DCSError on the field. Finally execute the validation with ValidatorValidate(...). Based on the results populate errorsToReport with list failed fields DSCError entries. When validation is done, try to track failed fields by calling dcsMultiTrack.

No comments: