Skip to content

Instantly share code, notes, and snippets.

@kid-cavaquinho
Last active August 29, 2015 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kid-cavaquinho/60ec941b979277f80c02 to your computer and use it in GitHub Desktop.
Save kid-cavaquinho/60ec941b979277f80c02 to your computer and use it in GitHub Desktop.
Helpers for Umbraco dictionary usage over MVC models
public class DictionaryDisplayNameAttribute : DisplayNameAttribute
{
private readonly string resourceName;
public DictionaryDisplayNameAttribute(string resourceName)
: base()
{
this.resourceName = resourceName;
}
public override string DisplayName
{
get
{
return DictionaryHelper.GetItemOrDefault(this.resourceName);
}
}
}
public class DictionaryRequiredAttribute : RequiredAttribute, IClientValidatable
{
public DictionaryRequiredAttribute() :
base()
{
ErrorMessage = DictionaryHelper.GetItemOrDefault("RequiredError");
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "required"
};
}
}
public class DictionaryStringLengthAttribute : StringLengthAttribute, IClientValidatable
{
public DictionaryStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
ErrorMessage = DictionaryHelper.GetItemOrDefault("MaxLengthError");
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "maxlength"
};
}
}
public class DictionaryRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
{
public DictionaryRegularExpressionAttribute(string pattern)
: base(pattern)
{
ErrorMessage = DictionaryHelper.GetItemOrDefault("RegexError");
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var ret = new List<ModelClientValidationRule>();
var mError = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "regex"
};
mError.ValidationParameters.Add("pattern", Pattern);
ret.Add(mError);
return ret;
}
}
//This is a sample Model explaining the usage of the helpers
//public class SampleUsageModel
//{
// [DictionaryDisplayName("Name")]
// [DictionaryRequired]
// public string Name { get; set; }
// [DictionaryDisplayName("Emailaddress")]
// [DictionaryRegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]
// [DictionaryRequired]
// public string Email { get; set; }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment