There are a few ways you could go about extending the ASP.NET validation controls, but i've come up with a quick way to use a customvalidator and get it to work perfectly as a requiredfieldvalidator.
The goal was I wanted to set the background-color of the element to red and display a required message when the user did not enter a value. The requirefieldvalidator does not allow you to do this normally (since you can't add a custom JS function to the extender.) You could do validation on the element itself, but I wanted something a little more reusable.
So here we create our custom validator:
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:CustomValidator ControlToValidate="txtName" runat="server"
ID="cvReqName" ClientValidationFunction="RequiredValidation"
ErrorMessage="Required" ValidateEmptyText="True"></asp:CustomValidator>
We make sure ValidateEmptyText is set to true and we call a generic RequiredValidation javascript function we created below:
// **********************************************************************************//
// This function is used for a asp.net custom validator control. Call this function //
// and it will determine what type of control is being used check the value and if //
// the value is blank then it will set the background color of the element to red //
// **********************************************************************************//
function RequiredValidation(sender, args) {
//debugger;
var ctrl = document.getElementById(sender.controltovalidate);
var ctrlValue;
// Determine the ctrl
switch (ctrl.tagName.toLowerCase()) {
case "input":
ctrlValue = ctrl.value;
break;
case "span":
ctrlValue = ctrl.innerHTML;
break;
case "select":
ctrlValue = GetDDLSelectedValue(ctrl);
break;
}
if (ctrlValue == "") {
ctrl.style.backgroundColor = "#E77471";
args.IsValid = false;
}
else {
ctrl.style.backgroundColor = "#FFFFFF";
args.IsValid = true;
}
}
This javascript function checks to see what type of control it is and if the value is "" if it is, it sets the isvalid flag on the validator and changes the background-color of the element to a red color. Simple as pie.