MVC Data Annotations ve Validation

Merhabalar, bugün DataAnnotation ve Validasyon konularına bakacağız.
MVC de code first ile tabloları oluşturuyorsanız DataAnnotation ile belirli kuralları validasyonları yönetebilirsiniz. Tabiki bu işlemler post işlemi esnasında olur.
Microsoft.jQuery.Unobtrusive.Validation yüklersek eğer bu bize kod tarafına gitmeden clientSide validasyon sağlar.


Microsoft.jQuery.Unobtrusive.Validation  gerçekten muazzam bir kütüphane olup clientside çalıştığı için hızlıdır.
Nuget ten ilgili kütüphaneyi ekledikten sonra
    <script src="~/scripts/jquery-3.0.0.min.js"></script>
    <script src="~/scripts/jquery.validate.min.js"></script>
    <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>

js lerini ilgili sayfaya eklemeniz yeterli olacaktır.

User.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Validation_DataAnnotations.Models
{
    // Data Annotations
    public class User
    {
        [DisplayName("Adınız"),Required]
        public string Name { get; set; }
        [DisplayName("Soyadınız"), Required]
        public string LastName { get; set; }
        [DisplayName("Yaş"), Required(ErrorMessage ="Lütfen Bir Yaş Giriniz"),Range(1,100)]
        public int Year { get; set; }
        [DisplayName("Email"), Required(ErrorMessage ="Email Alanını Giriniz "),]
        public string Email { get; set; }
        [DisplayName("Email2"), Required]
        public string Email2 { get; set; }
        [DisplayName("Kullanıcı Adı"),Required, MinLength(3), MaxLength(30)]
        public string UserName { get; set; }
        [DisplayName("Şifre"),Required,DataType(DataType.Password)]
        public string Password { get; set; }
        [DisplayName("Şifre Tekrar"), Required, DataType(DataType.Password),Compare(nameof(Password))]
        public string AgainPassword { get; set; }
    }
}


HomeController

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

namespace Validation_DataAnnotations.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View(new User());
        }
        [HttpPost]
        public ActionResult Index(User model)
        {
            if (model.UserName =="oktay")
            {
                //veri tabaınıda kullanıcı adı kontrolu yapılır
                ModelState.AddModelError("KullanıcıAdı", "Bu kullanıcı adı vardır");
            }
            return View(model);
        }
    }
}


Index.cshtml

@model Validation_DataAnnotations.Models.User

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

    <script src="~/scripts/jquery-3.0.0.min.js"></script>
    <script src="~/scripts/jquery.validate.min.js"></script>
    <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
       
        <div class="form-horizontal col-md-4 col-md-offset-4">
            <h4>User</h4>
            <hr />
            @Html.ValidationSummary(false, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Year, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Year, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Year, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.Email2, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email2, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Email2, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
                </div>
            </div>
   
            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(model => model.AgainPassword, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.AgainPassword, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.AgainPassword, "", 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>
</body>
</html>







Hiç yorum yok:

Yorum Gönder