开发者

Disable validation on certain fields

开发者 https://www.devze.com 2022-12-24 12:34 出处:网络
I\'ve got a ViewModel for adding a user with properties: Email, Password, ConfirmPassword with Required attribute on all properties. When editing a user I want the Password and ConfirmPassword propert

I've got a ViewModel for adding a user with properties: Email, Password, ConfirmPassword with Required attribute on all properties. When editing a user I want the Password and ConfirmPassword properties not to be req开发者_如何学运维uired.

Is there a way to disable validation for certain properties in different controller actions, or is it just best to create a seperate EditViewModel?


I like to break it down and make a base model with all the common data and inhierit for each view:

class UserBaseModel
{
    int ID { get; set; }

    [Required]
    string Name { get; set; }       

    [Required]
    string Email { get; set; }               
    // etc...
}

class UserNewModel : UserBaseModel
{
    [Required]
    string Password { get; set; }

    [Required]
    string ConfirmPassword { get; set; }
}

class UserEditModel : UserBaseModel
{
    string Password { get; set; }
    string ConfirmPassword { get; set; }
}

Interested to know if there is a better way as well although this way seems very clean an flexible.


You could write a custom attribute that can test a condition and either allow an empty field or not allow it.

The below is a simple demo i put together for the guys here. You'll need to modify to suit your purposes/

    using System.ComponentModel.DataAnnotations;

    namespace CustomAttributes

    {

    [System.AttributeUsage(System.AttributeTargets.Property)]

    public class MinimumLength : ValidationAttribute

    {
        public int Length { get; set; }
        public MinimumLength()
        {
        }

        public override bool IsValid(object obj)
        {
            string value = (string)obj;
            if (string.IsNullOrEmpty(value)) return false;
            if (value.Length < this.Length)
                return false;
            else
                return true;
        }
    }
}

Model;

using CustomAttributes;

namespace Models
{
    public class Application
    {
        [MinimumLength(Length=20)]
        public string name { get; set; }
    }
}

Controller

 [AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Application b)
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    if (ModelState.IsValid)
    {
        return RedirectToAction("MyOtherAction");
    }
    return View(b);
}

enter code here
0

精彩评论

暂无评论...
验证码 换一张
取 消