Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
Hi Team

I want to validate when leaving the textbox on my form, but i able to validate on a client side, i havent experience using data-anotation in asp.net and need bit of a help. When leaving the textbox if its empty must validate using caption error.

What I have tried:

C#
<pre> <div class="form-group">
                                <input type="email" class="form-control" id="textEmail" placeholder="Enter Email" required="required">
                                <div>
                                    <label id="labelMessage" class="text-danger" style="display:none">Invalid email address.</label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type='text/javascript'>
        $(function () {
            //When the blur event occurs from your Textbox (you lose focus)
            $('#textEmail').blur(function () {
                var email = document.getElementById("textEmail").value;
                var expr = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
                if (!expr.test(email)) {
                    document.getElementById("labelMessage").style.display = "inline";
                }
                else {
                    document.getElementById("labelMessage").style.display = "none";
                }
            });
        });
    </script>
Posted
Updated 31-Jul-20 22:37pm

1 solution

Hi,

You can easily use the regular expression attribute and set the expression inside that attribute and it should be on top of a property of a class.

C#
[RegularExpression ("[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$", ErrorMessage = "Invalid Email")]
public string Email { get; set; }


Cheers,
Jin
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900