Created
February 14, 2013 15:30
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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