JumpStart # 10 – Display Validation Error Messages in different formats using JavaScript

 

Before looking at the code, Read about – What is JumpStart?

At times, instead of normal display of validation error messages (or even in the validation summary) on the page, we tend to display them in more user friendly manner. See the sample image below –

SampleValidationErrorDisplay

This Jumpstart deals with the using JavaScript to get the above shown validation error display formats. The main concentration laid on especially 3 different formats – 1) Water Marking 2) Error Images (beside TextBox) and 3) Alert Dialog. The before mentioned effects can be easily achieved with some quick JavaScript. In this tutorial, we use 3 JavaScript functions to get more flexible user interactivity with the page, they are – validate(), resetValidation(event) and singleValidation(event). In the following code sample we use three simple TextBox and RequiredFieldValidator pairs to demonstrate the validation error effects.

NOTE :-
  1. validate() JavaScript function – it is used with OnClientClick property of the Button control, by which the complete page is validated by iterating through the array of validators on the page using Page_Validators[] of ASP.Net Validation ClientSide API.
  2. resetValidation(event) JavaScript function – this function is used with OnFocus clientside event of input control, so that the invalid validation effect (at that moment of time) will be set to the default value i.e., valid effect.
  3. singleValidation(event) JavaScript function – this function is used in conjunction with OnBlur clientside event. And this function validate the individual input controls against their validators and correspondingly display the validation error effects of that particular control.

IMPORTANT :-

The concept is 100% logical solution. In JavaScript, check for validation of the validator, if the validation succeeds – flag the validation success effect, or else if the validation fails – flag the validation error effect.

================================================================================================

Default.aspx

This page incorporates the UI – TextBoxes and RequiredFieldValidators and also implements the JavaScript functions to validate input data.

================================================================================================

<%@ Page Language="C#"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">   
    protected void Page_Load(object sender, EventArgs e)
    {
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript" src="ValidationErrorDisplay.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Color Validation TextBox :</td>
                <td>
                    <asp:TextBox 
                        ID="ColorTextBox" 
                        runat="server" 
                        onfocus="resetValidation(this)" 
                        onblur="singleValidation(this)">
                    </asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator 
                        ID="ColorValidator" 
                        ControlToValidate="ColorTextBox" 
                        runat="server">
                    </asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Image Validation TextBox :
                </td>
                <td>
                    <asp:TextBox 
                        ID="ImageTextBox" 
                        runat="server" 
                        onfocus="resetValidation(this)" 
                        onblur="singleValidation(this)">
                    </asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator 
                        ID="ImageValidator" 
                        ControlToValidate="ImageTextBox" 
                        runat="server">
                    </asp:RequiredFieldValidator>                    
                    <img 
                        id="ColorImage" 
                        width="15" 
                        height="15" 
                        style="display:none" />
                </td>
            </tr>
            <tr>
                <td>
                    Alert Validation TextBox :
                </td>
                <td>
                    <asp:TextBox 
                        ID="AlertTextBox" 
                        runat="server" 
                        onfocus="resetValidation(this)" 
                        onblur="singleValidation(this)">
                    </asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator 
                        ID="AlertValidator" 
                        ControlToValidate="AlertTextBox" 
                        runat="server">
                    </asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button 
                        ID="btnSubmit" 
                        runat="server" 
                        Text="Validate" 
                        OnClientClick="return validate()" />
                </td>
                <td>
                </td>
                <td>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

================================================================================================

ValidationErrorDisplay.js

This is the JavaScript file, incorporates the 3 – JavaScript Functions i.e.,  validate(), resetValidation(event) and singleValidation(event).

================================================================================================

function validate() {
    var i;
    if (Page_ClientValidate()) {
        return true;
    }
    else {
        for (i = 0; i < Page_Validators.length; i++) {
            var validatorControl = document.getElementById(Page_Validators[i].getAttribute("ID").toString());
            if (!Page_Validators[i].isvalid) {
                if (validatorControl.id == 'ColorValidator') {
                    document.getElementById(validatorControl.controltovalidate).style.backgroundColor = '#FF5050';
                }
                if (validatorControl.id == 'ImageValidator') {
                    document.getElementById('ColorImage').src = 'images/wrong.png';
                    document.getElementById('ColorImage').style.display = 'block';
                }
                if (validatorControl.id == 'AlertValidator') {
                    alert('Enter a value in Alert TextBox');
                }
            }
            else {
                if (validatorControl.id == 'ColorValidator') {
                    document.getElementById(validatorControl.controltovalidate).style.backgroundColor = '#66FF33';
                }
                if (validatorControl.id == 'ImageValidator') {
                    document.getElementById('ColorImage').src = 'images/correct.png';
                    document.getElementById('ColorImage').style.display = 'block';
                }
            }
        }
        return false;
    }
}


function resetValidation(event) {
    if (event.id == 'ColorTextBox') {
        document.getElementById(event.id).style.backgroundColor = '#FFFFFF';
    }
    if (event.id == 'ImageTextBox') {
        document.getElementById('ColorImage').style.display = 'none';
    }
}


function singleValidation(event) {
    for (i = 0; i < Page_Validators.length; i++) {
        var validatorControl = document.getElementById(Page_Validators[i].getAttribute("ID").toString());
        if (event.id == 'ColorTextBox' && validatorControl.controltovalidate == 'ColorTextBox') {
            ValidatorValidate(validatorControl);
            if (!validatorControl.isvalid) {
                document.getElementById(event.id).style.backgroundColor = '#FF5050';
            }
            else {
                document.getElementById(event.id).style.backgroundColor = '#66FF33';
            }
            break;
        }
        if (event.id == 'ImageTextBox' && validatorControl.controltovalidate == 'ImageTextBox') {
            ValidatorValidate(validatorControl);
            if (!validatorControl.isvalid) {
                document.getElementById('ColorImage').src = 'images/wrong.png';
                document.getElementById('ColorImage').style.display = 'block';
            }
            else {
                document.getElementById('ColorImage').src = 'images/correct.png';
                document.getElementById('ColorImage').style.display = 'block';
            }
            break;
        }
        if (event.id == 'AlertTextBox' && validatorControl.controltovalidate == 'AlertTextBox') {
            ValidatorValidate(validatorControl);
            if (!validatorControl.isvalid) {
                alert('Enter a value in Alert TextBox');
            }
            break;
        }
    }
}
NOTE :-

Important points on JavaScript Functions

  1. Page_Validators[] array is used to iterate through the validators on the page.
  2. Page_Validators[i].isvalid is used to check for validation of a validator.
  3. ValidatorValidate(val) function of asp.net clientside validation API is used to validate a particular validator at a time.
  4. validatorControl.controltovalidate is used to get the id of the control which is being validated by that particular validator (here – validatorControl is a validator control with id – Page_Validators[i].getAttribute("ID").toString()).
  5. For more info on ASP.NEt ClientSide Validation – Click Here.

================================================================================================

Folder Structure

The folder structure in the solution explorer of VS 2010.

================================================================================================

FolderStructure-DifferentValidationErrorDisplays

================================================================================================

OUTPUT

================================================================================================

Disclaimer:

All coding and suggestions made in the above discussion is strictly in point of view of the author. It is neither mentioned any where nor even concluded that this is the only possible way to go with, as there will be always a chance for a new approach in achieving the same requirement (in context of programming). The above mentioned code is strictly written and explained for the sake of new comers to C# and ASP.NET world.

You may also like...

  • Enos

    Thanks,

    here is my request below..it is similar as yours but i need the following to happen,

    I have created a web page with more than 10 text boxes, i know how to use all validations from vs . now i want to apply validations using Javascript. here are my problems below.

    1.For Email;

    I want a textbox to change border color to red if it is invalid email, belows it is what i have so far..

    ar emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i

    function checkmail(e){
    var returnval=emailfilter.test(e.value)
    if (returnval==false){
    alert(“Please enter a valid email address.”)
    e.select()
    }
    return returnval
    }

    on the text box;

    <asp:TextBox ID="txtEmail" name="email" onClick="return checkmail(this.myemail)" runat="server"

    2.For Numbers

    This texbox will only allows numbers only ,I want a textbox to change border color to red if it is invalid input, belows it is what i have so far..

    function numeralsOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
    ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode 57)) {
    alert(“Enter numbers only in this field.”);
    return false;
    }
    return true;
    }

    on the text box;

    <asp:TextBox ID="txtFullName" onkeypress="return numeralsOnly(event)" runat="server"

    2.For Letters

    This texbox will only allows Letters only,I want a textbox to change border color to red if it is invalid input, belows it is what i have so far..

    function lettersOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
    ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode 90) &&
    (charCode 122)) {
    alert(“Enter letters only.”);
    return false;
    }
    return true;
    }

    on the text box;

    <asp:TextBox ID="txtFullName" onkeypress="return lettersOnly(event)" runat="server"

    Thanks for your help…. ::)