I don't know if you can use DataTypeAttributes
as parameters in a function.
But as an easy way to just check if it is a valid email notation you could use this code:
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == email;
}
catch {
return false;
}
EDIT 1:
As mentioned from Mark Vincze here on his blog, you could create a new ActionFilterAttribute
like this when you want to have attributes in your action parameters.
public class ValidateActionParametersAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
{
var parameters = descriptor.MethodInfo.GetParameters();
foreach (var parameter in parameters)
{
var argument = context.ActionArguments[parameter.Name];
EvaluateValidationAttributes(parameter, argument, context.ModelState);
}
}
base.OnActionExecuting(context);
}
private void EvaluateValidationAttributes(ParameterInfo parameter, object argument, ModelStateDictionary modelState)
{
var validationAttributes = parameter.CustomAttributes;
foreach (var attributeData in validationAttributes)
{
var attributeInstance = CustomAttributeExtensions.GetCustomAttribute(parameter, attributeData.AttributeType);
var validationAttribute = attributeInstance as ValidationAttribute;
if (validationAttribute != null)
{
var isValid = validationAttribute.IsValid(argument);
if (!isValid)
{
modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name));
}
}
}
}
}
But this also just workes for Actions
. Because the ModelState
-Class was created to make it easier to check if an incoming binding is valid or not and not just to validate random objects. Here is more about that.
So in your case when AddEmail
is a 'normal' method and not an Action
you should not use this. In this case, use another validation method such as my first answer.
And if you want to read even more about validation, take a look at this blog post from Brad Wilson.