Question

I have the following Model:

public class DeliveryTracking
    {
        public string TrackingRef { get; set; }
        public string SalesID { get; set; }
        public string PackingSlipID { get; set; }
        public string Type { get; set; }
    }

I have an Action which set's some values for this model and then returns it to a view like so:

DeliveryTracking track = new DeliveryTracking();
track.SalesID = 123;
track.PackingSlipID = 456;
track.Type = "TNT";
return PartialView("_GetForm", track);

In that View I then have a form in which I'm able to set the TrackingRef like so:

@Html.HiddenFor(model => model.SalesID)
@Html.HiddenFor(model => model.PackingSlipID)
@Html.HiddenFor(model => model.Type)
@Html.EditorFor(model => model.TrackingRef)
<input type="submit" value="Submit" />

I want this TrackingRef to validate against different lengths depending on the Type of Tracking I'm using. For example, I've set the tracking type to TNT, so I want it to have a minlength of 7, but if I set it to UPS I want it to have a minlength of 8, is this possible? I know I can set the MinLength attribute in my model, but I want it to be dynamic/conditional based upon the type of tracking Im using.

Était-ce utile?

La solution

you can add your conditional validation rules. Make your model inherit fom IValidatableObject and implement the Validate method. You could do something the below(I haven't test it):

public class DeliveryTracking : IValidatableObject
    {
        public string TrackingRef { get; set; }
        public string SalesID { get; set; }
        public string PackingSlipID { get; set; }
        public string Type { get; set; }
    }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
{ 
    if (Type ==typeOf(TNT) && TrackingRef.Length < 7
        return new ValidationResult("TrackingRef must be 7.");
    if(Type == typeOf(UPS ) && TrackingRef.Length < 8)
        return new ValidationResult("TrackingRef must be 8.");
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top