Skip to content

Instantly share code, notes, and snippets.

@DTTerastar
Created February 14, 2013 15:30
Show Gist options
  • Save DTTerastar/4953554 to your computer and use it in GitHub Desktop.
Save DTTerastar/4953554 to your computer and use it in GitHub Desktop.
Validate by using IValidatableObject, or by DbEntityValidationException. The asterisk control with the correct member name will show which fields need updating, while all error messages will show in ValidationSummary.
public static class AsteriskValidation
{
public static void Validate(this Page page, IValidatableObject validatableObject, ValidationContext context = null)
{
foreach (ValidationResult error in validatableObject.Validate(context))
page.Validators.Add(new ErrorValidator(error));
}
public static void Validate(this Page page, DbEntityValidationException ex, ValidationContext context = null)
{
foreach (DbValidationError error in ex.EntityValidationErrors.Where(a => !a.IsValid).SelectMany(a => a.ValidationErrors))
page.Validators.Add(new ErrorValidator(error));
}
}
public class ErrorValidator : IValidator
{
public ErrorValidator(ValidationResult validationResult)
{
ErrorMessage = validationResult.ErrorMessage;
MemberNames = validationResult.MemberNames;
}
public ErrorValidator(DbValidationError validationResult)
{
ErrorMessage = validationResult.ErrorMessage;
MemberNames = new[] {validationResult.PropertyName};
}
public IEnumerable<string> MemberNames { get; set; }
public void Validate()
{
}
public bool IsValid
{
get { return false; }
set { throw new InvalidOperationException(); }
}
public string ErrorMessage { get; set; }
}
public class Asterisk : Label
{
public string MemberName { get; set; }
protected bool EvaluateIsValid()
{
IEnumerable<ErrorValidator> errorValidators = Page.Validators.Cast<object>().OfType<ErrorValidator>().Where(ev => ev.MemberNames.Any(a => a == MemberName));
return errorValidators.All(ev => ev.IsValid);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ForeColor = Color.Red;
Text = "*";
}
public override void RenderControl(HtmlTextWriter writer)
{
if (EvaluateIsValid()) return;
base.RenderControl(writer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment