How about using an IValidator instead? http://www.david-tec.com/2012/06/EPiServer-7-Preview---IValidator-interface/
Hi,
I also think that Per's idea of implementing validation using IValidate<T> is interesting.
When you use HttpContext.Current to resolve validated page url it will work only when saving/publishing in the web browser. If you try to save the page programmatically, for example in the Scheduled Job, then the Current context could be not relevant.
The IValidate could be used with any type. It could be used with a property or a with a whole Content. When you use it on the property level, like IValidate<XhtmlString> then you will get same effect as using ValidationAttribute. But you will not have access to validated page (and it will validate all XHtml strings in your system).
To get access to the content you could implement IValidate<YourPageModel>. Then in the Validate method you will validate the specific property (like the Xhtml property). Using UrlResolver you will be able to get page URL
public class MessageValidator : IValidate<ArticlePage> { IEnumerable<ValidationError> Validate(ArticlePage instance) { if (instance.Message.Length > 100) { // get URL to the page ServiceLocator.Current.GetInstance<UrlResolver>().GetUrl(instance.PageLink); return new[] { new ValidationError() { ErrorMessage = "Max length is 100", PropertyName = "Message", Severity = ValidationErrorSeverity.Error, ValidationType = ValidationErrorType.AttributeMatched } }; } return Enumerable.Empty<ValidationError>(); } }
IValidate is working pretty well.
The only drawback is that I can't use it as an attribute on a property but that isn't really necessary in this case.
Thanks, both of you.
I am writing a ValidationAttribute where I need to get the page that is currently being edited.
In other places I use UrlResolver.Current.Route(new UrlBuilder(HttpContext.Current.Request.Url)) to get the page.
But in my ValidationAttribute this returns null.
HttpContext.Current.Request.Url gives me "http://local/EPiServer/cms/Stores/contentdata/1076_5502" but the UrlResolver cannot translate it to content.
I've read somewhere that "HttpContext.Current.Handler as PageData" would give me a page but in this case the Handler is of the type "EPiServer.Shell.Services.Rest.RestHttpHandler" and casting it to PageData returns null.
Does anyone know if there are some other ways to get the current page or if there are some workarounds to this?