Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Can anyone help me to do this task. I have got a textbox that accept the email address. We need to validate the email address such that it has only "@gmail.com " extension. If the email address is not valid I need to make the div with red background and also display an error message that the email is not valid.

HTML
<div class="detailsRow" id="VAREmail">
           <div class="detailsLabel">
               @Html.LabelFor(m => m.VAREmail, Strings.VAREmail)
           </div>
           @Html.TextBoxFor(m => m.VAREmail, new { style = "width:50%" })
           @Html.ValidationMessageFor(m => m.VAREmail)
       </div>


What I have tried:

I tried using a javascript but I couldn't make it

var email = document.getElementById("VAREmail").next().value;
var filter = ^(?i)[A-Z0-9._%+-]+@(gmail.com);
if(!filter.test(email))
{
document.getElementById("VAREmail").style.backgroundColor = "maroon";
}
Posted
Updated 13-May-16 9:07am
v2

Try a regex:
^[\w!#$%&'*+-/=?^_`{|}~]{1,64}@gmail.com$
Should do it.
 
Share this answer
 
Add the RegularExpression attribute[^] to the property in your model:
C#
[RegularExpression(@"^[^@]+@gmail\.com$", ErrorMessage = "Please enter a GMail address.")]
public string VAREmail { get; set; }

Alternatively, don't let the user type the domain at all:
C#
[RegularExpression(@"^[^@]+$", ErrorMessage = "Please enter a GMail account.")]
public string VAREmail { get; set; }

public string RealEmail
{
    get { return string.IsNullOrWhiteSpace(VAREmail) ? string.Empty : VAREmail + "@gmail.com"; }
}

HTML
<div class="input-group">
    @Html.TextBoxFor(m => m.VAREmail)
    <div class="input-group-addon">@gmail.com</div>
</div>
 
Share this answer
 
Comments
user 3008 13-May-16 10:20am    
Thanks for your reply. If I code as you said I am getting the error message but I couldn't include a styling if the validation returns false.
Richard Deeming 13-May-16 10:25am    
You'll need to override the default "highlight" and "unhighlight" methods for the jQuery Validation[^] script.

For Bootstrap, I tend to use:
$.validator.setDefaults({
   highlight: function (element, errorClass, validClass) {
      $(element).closest('.form-group').removeClass(validClass).addClass('has-error');
   },
   unhighlight: function (element, errorClass, validClass) {
      $(element).closest('.form-group').removeClass('has-error').addClass(validClass);
   }
});
Here is an online tool to check RegEx. It display your RegEx expression visually in a nice graph, and allow you to text some expressions for matching.


Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
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