Search code examples
c#asp.netunobtrusive-validation

How to verify on valid


How can I show a green checkbox image beside textbox on valid usage ?
I'm trying to show this when the user passed to next textbox.

Here is my code for invalid usage

<asp:TextBox ID="TextBoxEMail" runat="server" ValidationGroup="Valid1"></asp:TextBox>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ErrorMessage="EMail is invalid"
ControlToValidate="TextBoxEMail"
ValidationGroup="Valid1" Display="Dynamic" ForeColor="Red"
ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*
[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"></asp:RegularExpressionValidator>

Solution

  • You can do it by using JavaScript (or jQuery). Here is an example of javascript.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs"     Inherits="WebApplication1.Test" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <link type="text/css" rel="stylesheet" href="Content/Site.css" />
        <title></title>
    
        <script type="text/javascript">
            function checkMailAddress(tb) {
                var regEx = RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
                var img = document.getElementById("imgValidate");
                if (regEx.test(tb.value)) {
                    img.style.display = "block";
                }
                else
                    img.style.display = "none";
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="txtEmail" runat="server" onchange="checkMailAddress(this)"></asp:TextBox>
                <asp:Image ID="imgValidate" runat="server" Height="18px" ImageUrl="~/Images/Ok.png" Width="22px" CssClass="validationImage" />
    
            </div>
        </form>
    </body>
    </html>
    

    And in the site.css :

    .validationImage
    {
        display:none;
    }
    

    The site.css is in the Content folder in the project. And the image Ok.png is in the Images folder.