【问题标题】:ASP.Net Core MVC - Custom validationASP.Net Core MVC - 自定义验证
【发布时间】:2020-06-10 16:29:19
【问题描述】:

我在 asp.net 上使用 Code First,我有以下课程:

public class Producto
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ProductoId { get; set; }
    [Remote(action: "VerifySku", controller: "Producto", ErrorMessage = "El sku ya está asignado a un producto")]
    [DisplayName("SKU")]
    public string Sku { get; set; }
    [Required(ErrorMessage = "Seleccione categoría")]
    [DisplayName("Categoria")]
    public Guid SubCategoriaProductoId { get; set; }
    [DisplayName("Categoria")]
    public SubCategoriaProducto SubCategoriaProducto { get; set; }
    public string Marca { get; set; }
    [Required(ErrorMessage = "Ingrese nombre")]
    [Remote(action: "VerifyName", controller: "Producto", ErrorMessage = "El producto ya existe")]
    public string Nombre { get; set; }
    public string Detalle { get; set; }
    [Required(ErrorMessage = "Ingrese precio")]
    public int Precio { get; set; }
    public bool PorEncargo { get; set; }
    [Remote(action: "VerifyStock", controller: "Producto", AdditionalFields = nameof(PorEncargo))]
    public int Stock { get; set; }
    [DefaultValue(1)]
    public int EstaActivo { get; set; }
    public virtual ICollection<ImagenProducto> Imagenes { get; set; }
}

我需要添加一个自定义验证,只要 PorEncargo 字段为 false,您就必须在其中 Require stock。 我在 ASP.Net Core 中没有找到任何方法。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc ef-code-first code-first


    【解决方案1】:

    我需要添加一个自定义验证,只要 PorEncargo 字段为 false,您就必须在其中 Require stock。

    public int Stock { get; set; }
    

    this doc,您可以发现.NET Core 3.0 及更高版本中的验证系统将不可为空的参数或绑定属性视为具有[Required] 属性。

    通常,如果int 类型属性(例如Stock)的输入大于0,而不是null,则我们有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多