asp.net MVC DataAnnotations -
please ask if can't understand i'm asking.
i have created custom validateattribute
viewmodel
i created validate properties depend property of viewmodel
if (user checked "01" or "09" qruplist)
- company name needed
- name,surname , lastname not needed
else
- company name not needed
- name,surname , lastname needed
i have viewmodel 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}' 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 it? wrong in validationattribute
s?
we looked @ validation using data annotations few months back, , decided better use fluent validation, had complex business rules , logic have taken effort realise data annotations. have @ documentation, , see fluent validation makes things easy.
sorry, did not sooner: check fluent validation here
your rule like. syntax not tested, sure able figure 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 )); } }
Comments
Post a Comment