Thursday, December 10, 2009

ASP.Net – Custom Validator – Setting the error message in client script

Question: How do you set the error message in the Client Validation Script.

Answer: If the client validation method is called CheckEntry, then your code would need to look like this:

<script type="text/javascript" language="javascript">
    function CheckEntry(sender, args) {
        ctrl1 = document.getElementById("<%=ctrlToValidate1.ClientID%>");
        ctrl2 = document.getElementById("<%=ctrlToValidate2.ClientID%>");

        if (isBlank(ctrl1 .value) && isBlank(ctrl1 .value)) {
                args.IsValid = false; 
                sender.errormessage = "Please provide atleast one search criteria"
                return;
            }
        }
        args.IsValid = true;
        return;
    }
    
    function isBlank(str) {
        str = ValidatorTrim(str);
        if (str == null || str.length < 1)
            return true;
        else
            return false;
    }
</script>

The error message is updated via the sender.errormessage property. The “ValidatorTrim” method is provided by a method from JavaScript that ASP.Net injects for you into the page whenever you use a validation control.

Simple and Easy!

1 comment:

w3c said...

Nice information, I really appreciate the way you presented.Thanks for sharing..

http://www.w3cvalidation.net/