Custom Validation

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.

Implementing server-side validation

  1. Open the Menu.aspx file
  2. Try and create an order with a total of 4 items and you should find this works, add any more or less items and the page will error
  3. The first step is to add a custom validator to the page, so drag one from the toolbox onto an appropriate location on the page
  4. Set appropriate values for the 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 controls
  5. In Split (or Design) view, double click on the validator. This will take you into the Menu.aspx.cs file, and create a method for implementing a validation check, and will appear similar to that shown below (the exact method name will vary depending on what ID the validator has)
    protected void cvalStarter_ServerValidate(object source, ServerValidateEventArgs args)
  6. 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

    In order to determine whether the input is valid in this instance, we need to check the input for each of the drop down lists and check that a total of 4 items have been selected. Add code inside the braces to do just that:
    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;
            args.IsValid = false;
  7. To finish implementing validation server-side we just need to modify the event handler for the button, so that it checks the page is valid before creating the order. Add the following code in the btnOrder_Click method, replacing the comment with the existing code:
    if (Page.IsValid)
        //existing btnOrder_Click code goes here
  8. Load the page in a browser and input some valid and invalid data - you should see the validation message appear for incorrect data, but only after the page has been posted back to the server

Implementing client-side validation

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

  1. In the <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;
  2. The final step is to set the ClientValidationFunction property of the Custom validator control to the name of the method created above: validateStarter
  3. You should now be able to run the page, and the user will be notified of invalid data by the JavaScript function, instead of the page having to post to the server