DEV Community

Nguyễn Thanh Hòa
Nguyễn Thanh Hòa

Posted on

 

ASP.NET MVC 5 Form Validation

Today, I do a Form Validation in ASP.NET MVC 5, I have information validation enter form
Begin

  • create project ASP.NET MVC 5 : File->New project->choose ASP.NET MVC 5
  • Click right project -> choonse Manager Nutget Packager -> search Entity Framework ->Installing
  • Click right App_Data directory in project -> create database name="db_website"
  • Create table Users in database

Ok, The connect to database, we need add command the followwing code below,you copy it and add to Web.config file in project directory, example database name="db_website" and db_website.mdf file database in App_data directory

<connectionStrings>
    <add name="db_website" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=db_website;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\db_website.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>

We have table Users, the figure following below
ASP.NET MVC 5 Form Validation - hoanguyenit.com

Ok, we need create User Model in Models directory, set data attributes is table Users

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Validation;
namespace FormValidation.Models
{
    public class User
    {
        [Key, Column(Order = 1)]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int idUser { get; set; }
        [Required]
        [StringLength(50,MinimumLength =3)]
        public string FirstName { get; set; }
        [Required]
        [StringLength(50, MinimumLength = 3)]
        public string LastName { get; set; }
        [Required]
        [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
        public string Email { get; set; }

        [Required]
        [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$")]
        public string Password { get; set; }

        [NotMapped]
        [Required]
        [Compare("Password")]
        public string F_Password { get; set; }

        public string FullName()
        {
            return this.FirstName + " " + this.LastName;
        }
    }
}
  • Required: The compulsory enter form
  • StringLength(): two parameter(maximunlength, minimumLength) Example: StringLength (150) or StringLength (150, MinimumLength = 3)
  • RegularExpression: we use a regular expression form validation Example: Check Email
[RegularExpression (@ "[A-Za-z0-9 ._% + -] + @ [A-Za-z0-9 .-] + \. [A-Za-z] {2, 4} ")]

We can set message error and confirm email

[RegularExpression (@ "[A-Za-z0-9 ._% + -] + @ [A-Za-z0-9 .-] + \. [A-Za-z] { 2,4} ", ErrorMessage =" Email doesn't look like a valid email address. ")]
[ Compare ("Email")]

Example

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
public string Email { get; set; }
[Compare("Email")]
public string EmailConfirm { get; set; }

Okay, based on the above example, let's check the password to see if the use
enter twice is the same, in the password entry step, we force the user to enter a lowercase letter, a capital letter, a number, and a character,particular

[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,15}$")] 

[NotMapped]:use the expression, for attribute fields not in the Users table, because the User.cs entity model will represent each data column in the User table

Next to connect the entity model queries together, we need to create a class that inherits from DbContext

Models/dbEntities.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace FormValidation.Models
{
    public class dbEntities : DbContext
    {
        public dbEntities() : base("db_website") { }
        public DbSet<User> Users { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Database.SetInitializer<demoEntities>(null);
            modelBuilder.Entity<User>().ToTable("Users");
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            base.OnModelCreating(modelBuilder);


        }

    }

}

After creating, we need to create action controller, create HomeController.cs file in Controllers folder

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

namespace FormValidation.Controllers
{
    public class HomeController : Controller
    {
        private dbEntities _db = new dbEntities();
        // GET: Home
        public ActionResult Index()
        {  
            return View();   
        }
        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(User _user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // Disable entity validation
                   _db.Configuration.ValidateOnSaveEnabled = false;
                   _db.Users.Add(_user);
                   _db.SaveChanges();
                   // return Json(_user, JsonRequestBehavior.AllowGet);
                      return RedirectToAction("Index");
                }
                return View();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                            validationErrors.Entry.Entity.ToString(),
                            validationError.ErrorMessage);
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }  
        }
    }
}

In the above code, if I can query the entity models, I need to declare the dbEntities class to query it.
ModelState.IsValid is used to check if the user has pressed submit
_db.Configuration.ValidateOnSaveEnabled = false to use to turn off auto validation of validation

Now we often create a view for the user to see, Views / Home / Register.cshtml

@model FormValidation.Models.User

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}

<div class="box-form">
    <div class="content-form">
        @using (Html.BeginForm("Register", "Home", FormMethod.Post))
        {@Html.AntiForgeryToken()
        <h2>Register Form</h2>
        <div class="form-group">
            @Html.LabelFor(m => m.FirstName)
            @Html.TextBoxFor(m => m.FirstName, "", new { @class = "txt-input", @placeholder = "First Name" })
            @Html.ValidationMessageFor(m => m.FirstName)
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.LastName)
            @Html.TextBoxFor(m => m.LastName, "", new { @class = "txt-input", @placeholder = "Last Name" })
            @Html.ValidationMessageFor(m => m.LastName)
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Email)
            @Html.TextBoxFor(m => m.Email, "", new { @class = "txt-input", @placeholder = "Email" })
            @Html.ValidationMessageFor(m => m.Email)
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Password)
            @Html.TextBoxFor(m => m.Password, "", new { @class = "txt-input", @placeholder = "Password" })
            @Html.ValidationMessageFor(m => m.Password)
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.F_Password)
            @Html.TextBoxFor(m => m.F_Password, "", new { @class = "txt-input", @placeholder = "Password Confirm" })
            @Html.ValidationMessageFor(m => m.F_Password)
        </div>
        <div class="form-group">
            <input type="submit" value="Submit" name="Submit" class="txt-input" />
        </div>
    }
    </div>
</div>

The CSS code tweaks the interface for Form Validation as follows


*{margin:0;padding:0}
    .box-form{
        width:500px;
        margin:auto;
        margin-top:20px;

    }
    .content-form{
        width:100%;
        padding:0px 20px;
        margin:5px 0px;
        box-sizing:border-box;
        box-shadow:0px 0px 5px rgba(0,0,0,0.5);
    }
    .content-form h2{
        text-align:center;
        font-size:30px;
        padding:10px;
         box-sizing:border-box;
    }
    .form-group{
        width:100%;
        padding:5px 0px;

    }
    label{
        display:block;
        padding:5px 0px;
        color:#ff6a00;
        font-weight:bold;
    }
    .txt-input{
        width:100%;
        padding:8px;
        box-sizing:border-box;
        border:none;
        outline:none;
        box-shadow:0px 0px 1px #000;
    }
    .field-validation-error{
       color: #ff0000;
        padding: 2px 0px;
        display: block;
        font-size: 12px;
    }
    input[type="submit"]{
        background:#ff6a00;
        color:#fff;
        font-weight:bold;
        margin-bottom:10px;
    }

Demo:
ASP.NET MVC5 Form Validation - hoanguyenit.com

The article: ASP.NET MVC5 Form Validation

Top comments (0)

12 Rarely Used Javascript APIs You Need

Practical examples of some unique Javascript APIs that beautifully demonstrate a practical use-case.