+ Reply to Thread
Results 1 to 2 of 2

Thread: REGEX : validate email form

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    40

    REGEX : validate email form

    I am creating an application which will be dedicated to a specific college campuses.
    I would like to ensure that, when a user signs up, and provides their email address, that it is their school provided email to ensure that only legitimate students have access to the service. and also More specifically, I just need to ensure that the email they enter is a .edu email address , Looks like regex is my solution , right ?

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    45
    I would create a Regular Expression Attribute and custom DataAnnotation. Register the annotation under Application_Start in your Global. Then you can use the validation as a DataAnnotation in your model both client and server side. I have a RegularExpressAttributes.cs class that contains all my commonly used regular expressions; all I do is drop it into my projects. If folks want it just let me know.

    The View:
    Code:
    <div class="editor-field span-7">
        @Html.LabelFor(model => model.EmailAddress)
        @Html.EditorFor(model => model.EmailAddress)
        @Html.ValidationMessageFor(model => model.EmailAddress)
    </div>
    Regular Expression Attribute
    Code:
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    namespace ProjectsMVC.Helpers
    {
        public class ValidateEmailAttribute : RegularExpressionAttribute
        {
    
            public ValidateEmailAttribute()
                : base(@)@"^\S?([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@someplace.com$") {}
        }   
    
        public class EmailValidator : DataAnnotationsModelValidator<ValidateEmailAttribute>
        {
            private readonly string _errorMessage;
    
            private readonly string _pattern;
    
            public EmailValidator(ModelMetadata metaData, ControllerContext context, ValidateEmailAttribute attribute)
                : base(metaData, context, attribute)
            {
                this._errorMessage = attribute.ErrorMessage;
                this._pattern = attribute.Pattern;
            }
            public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
            {
                var rule = new ModelClientValidationRegexRule(this._errorMessage, this._pattern);
                return new[] { rule };
            }
    
            #endregion
        }
    }
    Global.ascx.cs
    Code:
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(ValidateEmailAttribute), typeof(EmailValidator));
    }
    Lastly the Model, User.cs
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    using ProjectsMVC.Helpers;
    
    namespace ProjectsMVC.Models
    {
        [MetadataType(typeof(User_Validation))]
        public partial class User
        {
            public string ProperName
            {
                get
                {
                    return string.Format("{0} {1}", this.FirstName, this.LastName);
                }
            }
    
            public string DirectoryName
            {
                get
                {
                    return string.Format("{0}, {1}", this.LastName, this.FirstName);
                }
            }
    
            public string IsUserActive
            {
                get
                {
                    return Dictionaries.TrueOrFalse.First(t => t.Key == this.IsActive).Value.ToString();
                }
            }
        }
    
        public class User_Validation
        {
            [Display(Name = "eName")]
            [Required(ErrorMessage = "required")]
            [ValidateEname(ErrorMessage = "invalid")]
            public string UserName { get; set; }
    
            [Display(Name = "First DirectoryName")]
            [Required(ErrorMessage = "required")]
            public string FirstName { get; set; }
    
            [Display(Name = "Last DirectoryName")]
            [Required(ErrorMessage = "required")]
            public string LastName { get; set; }
    
            [Display(Name = "Email Address")]
            [Required(ErrorMessage = "required")]
            [ValidateEmail(ErrorMessage = "invalid")]
            public string EmailAddress { get; set; }
    
            [Display(Name = "Active User")]
            [Required(ErrorMessage = "required")]
            public bool IsActive { get; set; }
        }
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts