I understood how this is done. it is really simple and straightforward.
What I did was that I created my own RequiredAttribute . instead of using the built-in RequiredAttribute .
The only downside is that you will need to implement the logic of this validator yourself.
I know that some may consider redoing what is already there. (reinvent the wheel), but in this way I will have full control over the Validator logic and error message.
As you can see, the logic is implemented in the IsValid() method below.
Here is the RequiredAttribute class that I created:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] public sealed class RequiredAttribute : ValidationAttribute { private const string _defaultErrorMessage = // Error Message // Notice that i can include the filed name in the error message // which will be provided in the FormatErrorMessage Method public RequiredAttribute() : base(_defaultErrorMessage) { } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name); } public override bool IsValid(object value) { if (value == null || String.IsNullOrWhiteSpace(Convert.ToString(value))) return false; else return true; } }
Now, when it comes to using Validator, you will need to provide a full reference to your new class, as it will interfere with the standard built-in class System.ComponentModel.DataAnnotations.RequiredAttribute in my example above.
in my case it looks like this:
[Amaly.Data.Validators.Required] public string Username { get; set; }
Hope this was helpful.
source share