I’m having problems with getting my custom dataannotations to work, I’m trying to add a validation-attribute that validates that the UsergroupName for a Customer (CustomerID) is unique.
[MetadataType(typeof(UsergroupMetaData))]
public partial class Usergroup { }
public class UsergroupMetaData
{
[Required()]
public object CustomerID { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "UsergroupNameRequired")]
public object UsergroupName { get; set; }
[UniqueUsergroupName(????)]
// what to put here?
}
public class UniqueUsergroupName : ValidationAttribute
{
UsergroupRepository _rep = new UsergroupRepository();
public override bool IsValid(object value, int customerID)
{
var x = _rep.GetUsergroups().ByUsergroupName(value).ByCustomerID(customerID);
// what to put here?
return false;
}
}
the IsValid should return false if the “count >0”.
How do I fix this one so it works. GetUsergroups() returns IQueryable.
EDIT:
[MetadataType(typeof(UsergroupMetaData))]
public partial class Usergroup { }
public class UsergroupMetaData
{
public object CustomerID { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "UsergroupNameRequired")]
[UniqueUsergroupName(ErrorMessageResourceType= typeof(Resources), ErrorMessageResourceName = "UsergroupNameExists")]
public object UsergroupName { get; set; }
}
public class UniqueUsergroupName : ValidationAttribute
{
UsergroupRepository _rep = new UsergroupRepository();
public override bool IsValid(object value, int customerID)
{
int usergroups = _rep.GetUsergroups().ByCustomerID(customerID).ByUsergroupName(value.ToString()).Count();
return usergroups >0;
}
}
How can I pass the current CustomerID as a parameter?
/M
You can apply this approach
http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/
To include the ID property in your search, so that you check for all “other” UsergroupMetaData
that have the same UsergroupName.
Check it and tel me if you have trouble applying it to your scenario.
Edit: More explanation
My understanding is that you need to check whether there are other UsergroupMetaData objects with the same UsergroupName.
Let’s assume we’ll make the validator become on your entire class not the property:
No parameters are needed. Let’s see how the UniqueUsergroupName Validate() method will look like: