Reputation: 5016
Is there a quick way to default the error message for all your fields in a model?
I want the validation to return the text:
" * required "
...but dont want to manually set it on each field.
Thanks Paul
Upvotes: 3
Views: 518
Reputation: 1200
You could create a new HTML helper and then call into the underlying ValidationMessage
or ValidationMessageFor
helpers setting the message text as you do so.
Something based on ValidationMessageFor
would look like this:
public static class HtmlHelperExtensions {
public static IHtmlString ValidatorMessageWithMyTextFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) {
return htmlHelper.ValidationMessageFor<TModel, TProperty>(expression, "required *");
}
}
And you can add that to your view using
@Html.ValidatorMessageWithMyTextFor(m=>m.MyModelPropertyToValidate)
Of course that all works from the view side of the app and not the model side so it all depends where you would like to embed the messages. If it's the model side then AEM's solution is a good one.
Upvotes: 0
Reputation: 3257
you can write your custom Required Attribute
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class AEMRequiredAttribute: ValidationAttribute
{
private const string _defaultErrorMessage = "* required";
public AEMRequiredAttribute()
: base(_defaultErrorMessage)
{ }
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, "* required", name);
}
public override bool IsValid(object value)
{
if (value == null || String.IsNullOrWhiteSpace(value.ToString())) return false;
else return true;
}
}
call this attribute as below :
public partial class AEMClass
{
[DisplayName("Dis1")]
[AEMRequiredAttribute]
public string ContractNo { get; set; }
}
Upvotes: 3