Disable validation in specific fields

I have a ViewModel for adding a user with properties: Email, Password, ConfirmPassword with the required attribute for all properties. When editing a user, I want the Password and ConfirmPassword properties not to be required.

Is there a way to disable the verification of certain properties in different controller actions or is it simply better to create a separate EditViewModel?

+3
source share
2 answers

I like to break it down and create a basic model with all the common data and non-viable for each kind:

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

I am interested to know if there is a better way, although this way seems very clean and flexible.

+2
source

, .

, . /

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

;

using CustomAttributes;

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

 [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

Source: https://habr.com/ru/post/1738567/


All Articles