Reputation: 3257
Please ask if you can't understand what I'm asking.
I have created a custom ValidateAttribute
for my ViewModel
i created it for validate properties which depend from another property of ViewModel
if (user checked "01" or "09" from QrupList) Then
else
I have ViewModel as below
[ValidateForGroupAttribute("Group", "CompanyName")]
public partial class AbonentViewModel
{
[DisplayName("Şirkət")]
public string CompanyName { get; set; }
[DisplayName("Soyadı")]
[Required(ErrorMessage = "Soyadı vacibdir")]
public string Surname { get; set; }
[DisplayName("Qrup")]
[Required(ErrorMessage = "Qrup vacibdir")]
public string Group{ get; set; }
public SelectList GroupList { get; set; }
}
My custom ValidationAttribute
classes:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class ValidateForGroupAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' a müvafiq '{1}' daxil din";
public ValidateForGroupAttribute(string originalProperty, string confirmPropertyCompany)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmPropertyCompany = confirmPropertyCompany;
}
public string OriginalProperty { get; private set; }
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmPropertyCompany);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true).GetValue(value);
object confirmValueCompany = properties.Find(ConfirmPropertyCompany, true).GetValue(value);
if ((string)originalValue == "01" || (string)originalValue == "09")
return false;
else
return true;
}
}
How do I do it? What is wrong in my ValidationAttribute
s?
Upvotes: 1
Views: 384
Reputation: 3616
We looked at validation using data annotations a few months back, and decided it was better to use something like fluent validation, as we had complex business rules and logic that would have taken too much effort to realise with data annotations. Have a look at the documentation, and you will see fluent validation makes things like this easy.
Sorry, I did not get back sooner: Check fluent validation here
Your rule could look something like. Syntax not tested, but I am sure you will be able to figure it out.
public class AbonentViewModelValidator : AbstractValidator<AbonentViewModel> {
public AbonentViewModelValidator() {
RuleFor(model => model.CompanyName).NotEmpty().When(model => (model.GroupList.Id == 1 || model.GroupList.Id == 9 ));
RuleFor(model => model.Surname).NotEmpty().When(model => (model.GroupList.Id != 1 || model.GroupList.Id != 9 ));
RuleFor(model => model.Name).NotEmpty().When(model => (model.GroupList.Id != 1 || model.GroupList.Id != 9 ));
}
}
Upvotes: 2