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"
        args.IsValid = true;
    function isBlank(str) {
        str = ValidatorTrim(str);
        if (str == null || str.length < 1)
            return true;
            return false;

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!

No comments: