Tuesday, May 26, 2015

Custom DataAnnotations with client and server side both validation

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

namespace System.ComponentModel.DataAnnotations
{
    public class SumitValidation : ValidationAttribute, IClientValidatable
    {

        public override bool IsValid(object value)
        {
            string strValue = value as string;
            if (!string.IsNullOrEmpty(strValue))
            {

                return strValue.ToLower()=="sumit";
            }
            return true;
        }

        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            //yield return new ModelClientValidationRule() { ValidationType = "sumitvalidation", ErrorMessage = this.ErrorMessageString };

            var modelClientValidationRule = new ModelClientValidationRule
            {
                ValidationType = "sumitvalidation",
                ErrorMessage = FormatErrorMessage(metadata.DisplayName)
            };           
            yield return modelClientValidationRule;
        }
    }
}


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


namespace MVC5_Test.Controllers
{
    public class CustomAttributeController : Controller
    {
        //
        // GET: /CustomAttribute/
        //[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [HttpGet]
        public ActionResult Index()
        {
           
            return View();
        }


        [HttpPost]
        public ActionResult Index(CustomValidation customValidation)
        {
          

            return View();
        }
    }
}



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

namespace MVC5_Test.Models
{
    public class CustomValidation
    {
        [Required]
        [SumitValidation]
        public string name { get; set; }
    }
}




@model MVC5_Test.Models.CustomValidation
@Scripts.Render("~/bundles/jquery")
@{
    ViewBag.Title = "Index";
}

Index




@using (Html.BeginForm())
{
    @Html.TextBoxFor(m=>m.name)
    @Html.ValidationMessageFor(m=>m.name)
    
  
}



 

No comments:

Post a Comment

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...