开发者

Conditional Required Attribute for validation

开发者 https://www.devze.com 2022-12-24 22:35 出处:网络
We\'re trying to get a conditional开发者_C百科 attribute to work, case in point, there\'s a boolean (checkbox) that if checked, its related text is required. So, ideally we\'d have something like ...

We're trying to get a conditional开发者_C百科 attribute to work, case in point, there's a boolean (checkbox) that if checked, its related text is required. So, ideally we'd have something like ...

public bool Provision { get; set; }

[ConditionalRequirement(IsNeededWhenTrue = Provision)]
public string ProvisionText { get; set; }

Is this even possible?

Alternate idea (not as elegant?)

    public bool Provision2 { get; set; }

    [PropertyRequired(RequiredBooleanPropertyName = "Provision2")]
    public string Provision2Text { get; set; }

I'd hate to use the magic string method ... but any other ideas?


Ended up rolling my own. Basically you create a valiation method that does your normal check of yes, no, whatever and collects them in some kind of error collection. The rub with this is sending it BACK to the Model itself. So I got lazy and strongly typed it as such ...

public static void AddError<T>(this ErrorCollection errorCollection, Expression<Func<T, object>> expression, string friendlyUiName)
{
    var propertyName = GetPropertyName(expression.ToString(), expression.Parameters[0].Name);
    var propertyInfo = typeof (T).GetProperty(propertyName);
    var resultError = DetermineOutput(friendlyUiName, propertyInfo.PropertyType);
    errorCollection.Errors.Add(new ValidationError(propertyName, resultError));
}

so then you're validation statements have something like this in them ...

    if (FirstName.IsEmpty())
        EntityErrorCollection.AddError<SomeClass>(x => x.FirstName, "First Name");

Then within the controller, a simple check and port it BACK to the model if it (isn't valid of course) ...

    foreach (var error in someObject.EntityErrorCollection.Errors)
         ModelState.AddModelError(error.Property, error.Message);

There's probably a more cleaner way of doing this but so far, this has been working just fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号