Reputation: 2823
I followed a tutorial and made a custom remote validator
for my application so that it will work even if the javascript is disabled. It works the same as normal Remote
validations by having a specified controller
and action
and the optional ErrorMessage
.
Here is the full code:
public class RemoteEmailCheckAttribute : RemoteAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//get the controller
Type controller = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller", this.RouteData["controller"].ToString()).ToLower());
if (controller != null)
{
MethodInfo action = controller.GetMethods().FirstOrDefault(method => method.Name.ToLower() == this.RouteData["controller"].ToString().ToLower());
if (action != null)
{
object instance = Activator.CreateInstance(controller);
object response = action.Invoke(instance, new object[] { value });
if (response is JsonResult)
{
object jsonData = ((JsonResult)response).Data;
if (jsonData is bool)
{
return (bool)jsonData ? ValidationResult.Success : new ValidationResult(this.ErrorMessage);
}
}
}
}
return new ValidationResult(this.ErrorMessage);
}
public RemoteEmailCheckAttribute(string routeName)
: base(routeName)
{
}
public RemoteEmailCheckAttribute(string action, string controller)
: base(action, controller)
{
}
public RemoteEmailCheckAttribute(string action, string controller, string areaName)
: base(action, controller, areaName)
{
}
}
And this is how i set it on my property,
[RemoteEmailCheck("IsEmailTaken","Enrollment",ErrorMessage="Email is already in use. Please pick something else")]
public string email { get; set; }
my question is that, since i will be using this constructor
:
public RemoteEmailCheckAttribute(string action, string controller, string areaName)
: base(action, controller, areaName)
Since the third parameter is actually string
of any name, how was it able to get the specified ErrorMessage=" "
?
I have been checking/researching online and read about Named parameters
but they are somehow different, please clarify it to me.
Upvotes: 1
Views: 625
Reputation: 125342
When creating Attributes, Any public non-static read-write fields or properties are named parameters.
For more information see Creating Custom Attributes
Upvotes: 3