On some occasions none of the supplied validators provide the functionality required. Consider a takeaway menu where the user can select a total of four items from a choice of four different items: they may chose four of the same item, or one of each different item, or some other combination.
This scenario has been created in the Menu.aspx file in the validation starter project, which you may have downloaded if you completed the Validation tutorial.
Providing custom validation is a bit more tricky, as it involves us writing programming code to check valid options in our scenario both in C sharp, but also, if we want to offer client side validation, in JavaScript too.
ID
and ErrorMessage
properties, but in this case do not set the control to validate. We cannot set this because we are actually validating input across four controlsprotected void cvalStarter_ServerValidate(object source, ServerValidateEventArgs args)
{
}
The args
property of the method has a property named IsValid
and we set this value depending one the validity of the data input by the user
protected void cvalStarter_ServerValidate(object source, ServerValidateEventArgs args)
{
int countSeaweed = int.Parse(ddlCrispySeaweed.SelectedValue);
int countRibs = int.Parse(ddlSpareRib.SelectedValue);
int countWonton = int.Parse(ddlWonton.SelectedValue);
int countPrawnToast = int.Parse(ddlPrawnToast.SelectedValue);
if (countSeaweed + countRibs + countWonton + countPrawnToast == 4)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
btnOrder_Click
method, replacing the comment with the existing code:
Page.Validate();
if (Page.IsValid)
{
//existing btnOrder_Click code goes here
}
To provide more immediate feedback, which is particularly useful if the user has a slow connection, we need to implement a method in JavaScript to check for validity
<head>
section of the aspx page, add a script tag with the following code:
<script type="text/javascript">
function validateStarter(oSrc, args) {
var toast = document.getElementById("ddlPrawnToast").selectedIndex;
var seaweed = document.getElementById("ddlCrispySeaweed").selectedIndex;
var wonton = document.getElementById("ddlWonton").selectedIndex;
var ribs = document.getElementById("ddlSpareRib").selectedIndex;
args.IsValid = (toast + seaweed + wonton + ribs) == 4;
}
</script>
ClientValidationFunction
property of the Custom validator control to the name of the method created above: validateStarter