Conditional validation on model in MVC

后端 未结 4 421
半阙折子戏
半阙折子戏 2020-12-01 06:39

I have a view & model that I use for both the edit and the insert page for a record. One of the business requirements is that a certain field is required on edit but not

4条回答
  •  Happy的楠姐
    2020-12-01 07:32

    There is the MVC Foolproof library: http://foolproof.codeplex.com/

    For example you would need to have something like this in your model:

    [RequiredIfTrue("Required", ErrorMessage = "*")]
    [Range(0.0, (double)decimal.MaxValue)]
    [DisplayName("Cost")]
    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    public decimal ProposedCost { get; set; }
    
    public bool Required { get; set; }
    

    You would then need to set the Required property based on which form the model is going to.

    You will also need a hidden input field on the form to represent the Required property if you wish to perform client side validation.

    Hope that helps...

提交回复
热议问题