locked
mvc 5 email validation for multiple emails separated by semicolons RRS feed

  • Question

  • User1694748171 posted

    I tried to use  ReEx for  email validation but it's not working. I want to sent email to multiple recipient separated by simicolon or comma 

    my code is 

            [RegularExpression("^([a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:/.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])(;)?)+$", ErrorMessage = "Invalid email format.")]
    

    I want the ReEx allowed spaces between email separated with  simicolom or comma.

    Monday, March 22, 2021 4:35 PM

Answers

  • User475983607 posted

    luay20032003

    I used the regular expression as told me but as soon I added  semi to enter another email I got the error (Please enter a valid email address) 

    The code I posted works perfectly which you can use to verify your code.  Anyway, you specifically configure an HTML 5 email input and why you are receiving the error.

    @Html.EditorFor(model => model.Email_CC, 
    new { htmlAttributes = new { @class = "form-control", @PlaceHolder = "JohnDoe@tn.gov,AlanSmith@tn.gov", 
        @type = "email" } })

    https://www.w3schools.com/tags/att_input_type_email.asp

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 23, 2021 11:02 AM
  • User475983607 posted

    Ok I saw my mistaken ,and I have question how I can allowed spaces between email and also I need give user option to use semicolon or comma separation between emails ?

    Well, you add the space and comma to the regex.  If you are unsure then I recommend spending time learning RegEx syntax.  The update for your new requirements is rather simple if you understand a few RegEx fundamentals.

    I use the following site to write and test RegEx patterns. https://regex101.com/

    Keep in mind, the RegEx I provided does not cover all possible user entry mistakes and you'll still need server side validation if there is an error sending the email.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 23, 2021 1:26 PM
  • User1694748171 posted

    this will allowed white space and semicolon or coma separation 

    ^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25}(($)|( *[;,]+ *$)|( *[;,]+ *(?=[a-zA-Z0-9_\-\.]))))*$

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 23, 2021 1:47 PM

All replies

  • User323983933 posted

    I let Microsoft do the heavy lifting here:  Basically if you can create a MailAddress object, then the email address is OK.  Thusly:

    using System;
    using System.Net.Mail;
    
    namespace APP.Common
    {
        public class Emailer
        {
    
            public static bool EmailAddressOK(string Address)
            {
                bool answer = true;
                try
                {
                    MailAddress Addy = new MailAddress(Address);
                    answer = true;
                }
                catch (Exception)
                {
                    answer = false;
                }
                return answer;            
            }
        }
    }

    Then you just call it with the address you want checked.

        Emailer.EmailAddressOK("Bob@abc.net"); //true
        Emailer.EmailAddressOK("Bob&abc.net"); //false

    Note that this does not go out and verify that the email address is a real one, it just verifies the format.

    Monday, March 22, 2021 5:41 PM
  • User1694748171 posted

    I need to verified the email in client side, and I want to enter many email address seperate by comma or simicolon , you code is working only for one email address and that's not what I want.

    Monday, March 22, 2021 6:15 PM
  • User323983933 posted

    ...So if there are 15 addresses, and one is bad... you want false?  or an array of 15 booleans?

    Well this adjustment will handle the list, but it's still server side.

            /// <summary>
            /// returns true if all the addresses are OK
            /// </summary>
            /// <param name="Addresses">a semicolon list of all the addresses to check.</param>
            /// <returns></returns>
            public static bool EmailAddressOK(string Addresses)
            {
                string[] addressArray = Addresses.Split(';');
                bool answer = true;
                try
                {
                    foreach (string address in addressArray)
                    {
                        MailAddress Addy = new MailAddress(address);
                    }
                }
                catch (Exception)
                {
                    answer = false;
                }
                return answer;
            }

    Monday, March 22, 2021 6:27 PM
  • User1694748171 posted

    this code is not detecting the right email format like myemail@yahoo   that should be myemail@yahoo.com 

    Monday, March 22, 2021 6:41 PM
  • User323983933 posted

    try this:

    ^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$

    Monday, March 22, 2021 6:45 PM
  • User1694748171 posted

    can I use that in viewmodel ?

    [RegularExpression("^(([^<>()[\\]\\.,;:\\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,}))$", ErrorMessage = "Invalid email format.")]
            [Display(Name = "CC:")]
            public string Email_CC { get; set; }

    Monday, March 22, 2021 6:50 PM
  • User1694748171 posted

    I used 

    ^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$

    and I got error when enter comma or simicolon between emails 

    Monday, March 22, 2021 7:09 PM
  • User475983607 posted

    Use a standard email regex and add an optional semicolon on the end.  Google is your friend.

    https://stackoverflow.com/questions/4351349/regular-expression-for-delimited-email-address

    Monday, March 22, 2021 7:13 PM
  • User1694748171 posted

    I tried to use this code in view modle but as soon I add  simicolon then I got error message invalid email 

      [RegularExpression("^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25}(($)|( *;+ *$)|( *;+ *(?=[a-zA-Z0-9_\\-\\.]))))*$", ErrorMessage = "Invalid email format.")]
            [Display(Name = "CC:")]
            public string Email_CC { get; set; }

    Monday, March 22, 2021 7:22 PM
  • User475983607 posted

    Come on now... your code looks nothing like the example for accepting emails separated by an optional semicolon.   

    Monday, March 22, 2021 7:36 PM
  • User1694748171 posted

    That's what I need. but it keep give me error of invalid email as soon as i enter semicolon between two emails 

    Monday, March 22, 2021 7:40 PM
  • User475983607 posted

    I don't know what to do for you.  The sample works for me.  I tested the regex at the following site. https://regex101.com/

    (([a-zA-Z\-0-9\.]+@)([a-zA-Z\-0-9\.]+)[;]*)+

    Monday, March 22, 2021 7:57 PM
  • User1694748171 posted

    I have no idea why is not working on my view

        [RegularExpression("^(([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5}){1,25}(($)|( *;+ *$)|( *;+ *(?=[a-zA-Z0-9_\\-\\.]))))*$", ErrorMessage = "Invalid email format.")]
            [Display(Name = "CC:")]
            public string Email_CC { get; set; }

    and my view 

       <div class="row">
                        @Html.LabelFor(model => model.Email_CC, htmlAttributes: new { @class = "col-md-3", @style = "font-weight:bold; " })
                        <div class="col-md-7">
                            @Html.EditorFor(model => model.Email_CC, new { htmlAttributes = new { @class = "form-control", @PlaceHolder = "JohnDoe@tn.gov,AlanSmith@tn.gov", @type = "email" } })
                            @Html.ValidationMessageFor(model => model.Email_CC, "", new { @class = "text-danger" })
                        </div>
                    </div>

    Monday, March 22, 2021 8:02 PM
  • User1694748171 posted

    The pattern your use is not working for the case:

    me@yahoo.com,luay& 

    after semicolon is not valid email but still say match in ReEx link https://regex101.com/

    Monday, March 22, 2021 8:26 PM
  • User475983607 posted

    As far as I can tell you have not used any of suggested regex expressions.

    Below is my working example.

        public class EmailVm
        {
            [RegularExpression(@"^(([a-zA-Z\-0-9\.]+@)([a-zA-Z\-0-9\.]+)[;]*)+$", ErrorMessage = "Invalid email format.")]
            [Display(Name = "CC:")]
            public string Email_CC { get; set; }
        }
        public class FormController : Controller
        {
            private readonly ILogger<FormController> _logger;
            public FormController(ILogger<FormController> logger)
            {
                _logger = logger;
            }
    
            [HttpGet]
            public IActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public IActionResult Index(EmailVm model)
            {
                return Json(model);
            }
        }
    @model MvcDemo.Controllers.EmailVm
    
    @{
        ViewData["Title"] = "Index";
    }
    
    <h1>Index</h1>
    
    <h4>EmailVm</h4>
    <hr />
    <div class="row">
        <div class="col-md-4">
            <form asp-action="Index">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="Email_CC" class="control-label"></label>
                    <input asp-for="Email_CC" class="form-control" />
                    <span asp-validation-for="Email_CC" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
            </form>
        </div>
    </div>
    
    <div>
        <a asp-action="Index">Back to List</a>
    </div>
    
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
    

    Monday, March 22, 2021 8:35 PM
  • User475983607 posted

    The pattern your use is not working for the case:

    me@yahoo.com,luay& 

    after semicolon is not valid email but still say match in ReEx link https://regex101.com/

    I have no idea what you are asking or what you're doing.  The test case you shared above fails as expected on https://regex101.com/ and the example code I provided above.

    Monday, March 22, 2021 8:48 PM
  • User475983607 posted

    Sorry, I created an .NET 5 example.  Below is MVC 5 which works the same.

        public class EmailVm
        {
            [RegularExpression(@"^(([a-zA-Z\-0-9\.]+@)([a-zA-Z\-0-9\.]+)[;]*)+$", ErrorMessage = "Invalid email format.")]
            [Display(Name = "CC:")]
            public string Email_CC { get; set; }
        }
        public class GeneralController : Controller
        {
            [HttpGet]
            public ActionResult Index()
            {
                return View();
            }
            [HttpPost]
            public ActionResult Index(EmailVm model)
            {
                return Json(model);
            }
        }
    @model MvcDemo.Controllers.EmailVm
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <h4>EmailVm</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Email_CC, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email_CC, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email_CC, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    

    This assumes you have a jqueryval bundle.

        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate.js",
                            "~/Scripts/jquery.validate.unobtrusive.js"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css"));
            }
        }

    Otherwise, you need to refence the jquery unobtrusive validation. 

    Lastly, if you want server side validation then you must use the standard validation pattern.

            [HttpPost]
            public ActionResult Index(EmailVm model)
            {
                if (ModelState.IsValid)
                {
                    return Json(model);
                }
    
                return View(model);
            }

    Monday, March 22, 2021 9:03 PM
  • User323983933 posted

    that's because adding a semi at the end means there is another email address of "", which fails the pattern.  don't add a semi at the end.

    It's like this

    cats,dogs,chickens

    not

    cats,dogs,chickens,

    Monday, March 22, 2021 9:49 PM
  • User475983607 posted

    that's because adding a semi at the end means there is another email address of "", which fails the pattern.  don't add a semi at the end.

    It's like this

    cats,dogs,chickens

    not

    cats,dogs,chickens,

    The regex I proposed handles and ending semicolon.   

    I suspect the actual issue has to do with not enabling client side validation and not using standard server side validation patterns.

    Monday, March 22, 2021 9:54 PM
  • User1694748171 posted

    I used the regular expression as told me but as soon I added  semi to enter another email I got the error (Please enter a valid email address) 

    Tuesday, March 23, 2021 1:44 AM
  • User1694748171 posted

    this is my bundle config 

      public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-3.5.0.js",
                    "~/Scripts/jquery-ui.1.11.1.js",
                    "~/Scripts/jquery.inputmask.js",
                    "~/Scripts/jquery.cookie.js",            
                     "~/Scripts/jquery.maskedinput",
                    "~/Scripts/jquery.dropdown.min.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.validate.unobtrusive.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-2.8.3.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                    "~/Scripts/bootstrap.js",
                    "~/Scripts/respond.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                    "~/Content/TextArea",
                    "~/Content/jquery-ui.1.12.1.min.css",
                    "~/Content/jquery.dropdown.min.css",
                    "~/Content/bootstrap.css" 
                                                 ));
            }
        }

    this is my view 

    @model BoatSafetyExam.ViewModels.EmailViewModel
    
    @{
        ViewBag.Title = "Email";
        Layout = "~/Views/Shared/_AdminMasterLayout.cshtml";
    }
    <script src="~/Scripts/jquery-3.5.1.slim.js"></script>
    <script src="~/Scripts/popper.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <script src="~/Scripts/bootstrap-multiselect.js"></script>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
        <link href="~/Content/bootstrap-multiselect.css" rel="stylesheet" />
    
        <!-- Bootstrap core CSS -->
        <!-- Custom styles for this template -->
    
    
    </head>
    
    
    <body style="padding-top:90px;">
        <div class="active">
            @Html.Partial("_NavBar")
        </div>
        <div class="d-flex " id="wrapper">
            @Html.Partial("_InputValidation")
            @Html.Partial("SidemenuBar")
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @using (Html.BeginForm("sentEmail", "Email", FormMethod.Post, new { enctype = "multipart/form-data", id = "thisForm" }))
            {
                @Html.AntiForgeryToken()
    
                <br />
                <h4 class="indent1">Email to Proctors</h4>
                <div id="messageDiv" style="clear: left; display: block; color: red; width: 490px;">
                    @Html.Partial("_messageContainerNreq")
                </div>
                <hr />
                <div class="indent1 container" style="padding-right:30px;">
    
                    <div class="row">
                        @Html.LabelFor(model => model.Email_From, htmlAttributes: new { @class = "required col-md-3", @style = " font-weight:bold; " })
                        <div class="col-md-7">
                            @Html.EditorFor(model => model.Email_From, new { htmlAttributes = new { @class = "form-control", @style = "width:280px", @readonly = "" } })
                            @Html.ValidationMessageFor(model => model.Email_From, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <br />
                    <div class="row">
                        @Html.LabelFor(model => model.Email_To, htmlAttributes: new { @class = "col-md-3", @style = "font-weight:bold; " })
                        <div class="col-md-7" id="emailList">
                            @Html.ListBoxFor(model => model.EmailList, Model.EmailList, new { @class = "listbox" })
                            @Html.ValidationMessageFor(model => model.EmailList, "", new { @class = "text-danger" })
                        </div>
                    </div>
    
                    <br />
                    <div class="row">
                        @Html.LabelFor(model => model.Email_CC, htmlAttributes: new { @class = "col-md-3", @style = "font-weight:bold; " })
                        <div class="col-md-7">
                            @Html.EditorFor(model => model.Email_CC, new { htmlAttributes = new { @class = "form-control", @PlaceHolder = "JohnDoe@tn.gov,AlanSmith@tn.gov", @type = "email" } })
                            @Html.ValidationMessageFor(model => model.Email_CC, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <br />
    
                   
    
    
                   
                  
               
    
                  
    
                    <br />
                    <div class="row justify-content-md-center">
    
                        <button id="btnSave" type="submit" class="btn btn-info btn-sm " value="Save" ">
                            <i class="fa fa-envelope-o" aria-hidden="true"></i>
                            Send
                        </button>
    
                    </div>
                    <br />
                    <div class="row">
                        <div class="col-md-9">
    
                            <span class="card border-success mb-1" style="color:forestgreen; padding-left:5px">
                                The upload file formats  only "pdf,jpeg, jpg , png, gif, bmp" and the maximum image file size to 10 MB.
                            </span>
                        </div>
                    </div>
    
    
                </div>
    
            }
        </div>
    
    </body>
    
    </html>
    
    
     
    
     
    
     
     
     
    
    
    <style>
        .borderRed {
            border: 1px solid #CD0A0A;
            background-color: #ffeeee;
        }
    </style>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    
    
    

    this is my view mode

     public class EmailViewModel
        {
            
            [Display(Name = "From (Sender):")]
            public string Email_From { get; set; }
    
          
            [Required]
            [Display(Name = "To Proctor(s):")]
            public List<string> Email_To { get; set; }
    
            [RegularExpression(@"^(([a-zA-Z\-0-9\.]+@)([a-zA-Z\-0-9\.]+)[;]*)+$", ErrorMessage = "Invalid email format.")]
            [Display(Name = "CC:")]
            public string Email_CC { get; set; }
    
    }

    and this is my controller 

       public ActionResult Index(EmailViewModel model )
            {
              
                return view(model);
            }

    Tuesday, March 23, 2021 1:49 AM
  • User475983607 posted

    luay20032003

    I used the regular expression as told me but as soon I added  semi to enter another email I got the error (Please enter a valid email address) 

    The code I posted works perfectly which you can use to verify your code.  Anyway, you specifically configure an HTML 5 email input and why you are receiving the error.

    @Html.EditorFor(model => model.Email_CC, 
    new { htmlAttributes = new { @class = "form-control", @PlaceHolder = "JohnDoe@tn.gov,AlanSmith@tn.gov", 
        @type = "email" } })

    https://www.w3schools.com/tags/att_input_type_email.asp

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 23, 2021 11:02 AM
  • User1694748171 posted

    Ok I saw my mistaken ,and I have question how I can allowed spaces between email and also I need give user option to use semicolon or comma separation between emails ?

    Tuesday, March 23, 2021 1:07 PM
  • User475983607 posted

    Ok I saw my mistaken ,and I have question how I can allowed spaces between email and also I need give user option to use semicolon or comma separation between emails ?

    Well, you add the space and comma to the regex.  If you are unsure then I recommend spending time learning RegEx syntax.  The update for your new requirements is rather simple if you understand a few RegEx fundamentals.

    I use the following site to write and test RegEx patterns. https://regex101.com/

    Keep in mind, the RegEx I provided does not cover all possible user entry mistakes and you'll still need server side validation if there is an error sending the email.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 23, 2021 1:26 PM
  • User1694748171 posted

    this will allowed white space and semicolon or coma separation 

    ^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25}(($)|( *[;,]+ *$)|( *[;,]+ *(?=[a-zA-Z0-9_\-\.]))))*$

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 23, 2021 1:47 PM