Tuesday 5 January 2021

MVC - validate email - ensure it is from specified domain address

 

 Watch this example on YouTube:

 

1. Model

using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class User
    {
        public string Name { get; set; }

        [RegularExpression(@"^[a-zA-Z0-9._%+-]+(@abc\.ca|@abc\.com)$", ErrorMessage ="{0} - invalid format (must be @abc.com)")]
     public string Email { get; set; }
    }


2. View

@model WebApplication1.Models.User

@using (Html.BeginForm("Index", "Home"))
{
    @Html.TextBoxFor(x => x.Email)
    @Html.ValidationMessageFor(x => x.Email)

    <input type="submit" value="save" />
}


3. Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            User model = new Models.User();   
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(User model)
        {
            if (ModelState.IsValid)
            {

            }
            return View(model);
        }


No comments:

Post a Comment