Conditional validation on model in MVC

后端 未结 4 401
半阙折子戏
半阙折子戏 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条回答
  • 2020-12-01 07:19

    You could use the RequiredIf validation attribute from the MVC Foolproof Validation project. I've used it on projects to enable just the functionality you require.

    An alternative would be to use the RemoteAttribute and implement the logic yourself in a method.

    0 讨论(0)
  • 2020-12-01 07:21

    You can try on validation with:

    ModelState.Remove("ProposedCost");
    

    Or extending your model like this:

    public class NewModeViewModel : EditModeViewModel
    {
       public new decimal ProposedCost { get; set; }
    }
    

    and passing to the edit view.

    0 讨论(0)
  • 2020-12-01 07:29

    If you're on MVC3/.NET4, you can use IValidatableObject which exists specifically for such purposes.

    Quoting ScottGu,

    ...The IValidatableObject interface enables you to perform model-level validation, and enables you to provide validation error messages specific to the state of the overall model....

    You model would look like

    public class MyViewModel : IValidatableObject
    {
        public long? Id { get; set; }
        public decimal? ProposedCost { get; set; }
    
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
        { 
            if (Id != null && ProposedCost == 0) {
                yield return new ValidationResult("ProposedCost must be provided.");
            }
        }
    }
    

    and then in the controller,

    [HttpPost]
    public ActionResult Submit(MyViewModel model)
    {
        if (!ModelState.IsValid) {
            //failed - report an error, redirect to action etc
        }
        //succeeded - save to database etc
    }
    

    Otherwise, the most clean solution would be to use view models - UpdateViewModel where the property is required, and CreateViewModel where it's not required.

    0 讨论(0)
  • 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...

    0 讨论(0)
提交回复
热议问题