ASP.NET MVC 5 FORM VALIDATION

Nay tôi sẽ làm một cái Form Validation trong ASP.NET MVC 5, để xác thực thông tin người dùng nhập vào form xem có chính xác không
Chuẩn bị:

  • Tạo một project ASP.NET MVC 5: File->New project->choose ASP.NET MVC 5
  • Click right project -> choose Manager Nutget Packager -> Search Entity Framework -> Installing 
  • Click right thư mục -> tạo database name "db_website"
  • Create table Users trong Database

Vậy là bước chuẩn bị đã xong, để connect được với database ta cần phải thêm câu lệnh connect dưới đây vào Web.config, bạn nhìn thấy code dưới đây ta có khai báo name="db_website" và tên database là db_website.mdf mà ta vừa tạo ở bước đầu

<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>

Table Users trong database của ta như sau:

ASP.NET MVC 5 FORM VALIDATION

Ban đầu ta có tạo table Users, nên ta cần phải tạo một model User.cs trong thư mục Models/User.cs, trong thực thể User.cs này ta cần khai báo các trường cần có trong table Users của ta

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: ta dùng bắt buộc trường đó không được bỏ trống
StringLength(): có 2 tham số maximum length và MinimumLength, Example: StringLength(150) or StringLength(150, MinimumLength =3)
RegularExpression: ta dùng biểu thức chính quy kiểm tra xem, người dùng có nhập đúng yêu cầu chưa.

Example: kiểm tra Email
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]

Chỉnh sửa câu thông báo lỗi:
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}",ErrorMessage="Email doesn't look like a valid email address.")]
    
 Đồng thời nếu ta cần đối chiếu Email xác thực, xem người dùng xác nhận bước tiếp theo đúng hay chưa dùng thuộc tính sau
[Compare("Email")]

[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 ta dựa vào ví dụ trên, ta hãy kiểm tra password xem người dùng nhập hai lần có giống nhau không, trong bước nhập password mình bắt người dùng phải nhập một chữ thường, một chữ hoa, một chữ số, với một ký tự đặt biệt, yêu cầu phải có ít nhất các ký tự đó mới thành công

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

[NotMapped]: dùng biểu thức này, cho các trường thuộc tính không có trong table Users, nếu không có ta sẽ bị báo lỗi, vì mô hình thực thể User.cs sẽ đại diện cho từng cột dữ liệu trong table User

Tiếp theo để kết nối truy vấn được các mô hình thực thể lại được với nhau, ta cần tạo một class kế thừa từ DbContext, dùng ánh xạ các mô hình thực thể các table với nhau, để ta có thể truy xuất nó
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);


        }

    }

}

Sau khi tạo xong, ta cần tạo bộ điều khiển hành động, bạn tạo file HomeController.cs trong thư mục Controllers

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;
            }  
        }
    }
}

Trong đoạn code trên, nếu sử dụng được truy vấn các mô hình thực thể, tôi cần phải khai báo lớp dbEntities  để truy vấn tới nó
ModelState.IsValid dùng để kiểm tra người dùng có bấm submit chưa
 _db.Configuration.ValidateOnSaveEnabled = false dùng để tắt tính năng xác thực auto của validation 

Giờ ta hay tạo khung nhìn cho người dùng xem, 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>

Code CSS chỉnh giao diện cho Form Validation như sau

    *{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 MVC 5 FORM VALIDATION

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)