javascript - Custom ValidationAttribute not displaying error -
i wrote custom validationattribute check if email exists in db. error message not displayed, , validation occurs after submit form. html contains reference javascript files display messages still no result. nevertheless other attributes work fine , respective message displayed.
public class noduplicateemail : validationattribute { protected override validationresult isvalid(object value, validationcontext validationcontext) { var context = new mhotivocontext(); var email = validationcontext.objectinstance.gettype().getproperties( ).firstordefault(prop => isdefined(prop, typeof(noduplicateemail))); var emailvalue = (string)email.getvalue(validationcontext.objectinstance); if(context.users.firstordefault(x => x.email == emailvalue)!=null) return new validationresult("email in use!"); return validationresult.success; } }
[required(errormessage = "email required")] [datatype(datatype.emailaddress)] [display(name = "email")] [noduplicateemail]
the object value
parameter of isvalid
method contains value of email property var email
, var emailvalue
lines of code unnecessary. code should be
public class noduplicateemail : validationattribute { private const string _defaulterrormessage = "email {0} in use!" public noduplicateemail() : : base(_defaulterrormessage) { } protected override validationresult isvalid(object value, validationcontext validationcontext) { var context = new mhotivocontext(); if (value != null) { var email = (string)value; if(context.users.firstordefault(x => x.email == emailvalue) != null) { return new validationresult(formaterrormessage(email)); } } return validationresult.success; } }
however should not accessing database resources in validation attribute (that not responsibility , code impossible unit test). should using [remote]
attribute client side validation , calling service server side validation.
instead create service method returns value indicating valid (or add private method in controller
private bool isemailinuse(string email) { return context.users.any(x => x.email == email) }
and actionresult
client side validation
public jsonresult isuniqueemail(string email) // parameter name must match property name { bool isinuse = isemailinuse(email); return json(!isinuse, jsonrequestbehavior); }
and apply remoteattribute
property
[remote("isuniqueemail", yourcontrollername, errormessage = "the email in use")] public string email { get; set; }
and finally, in post method (in case of malicious user, or javascript has been disabled)
public actionresult yourmethod (yourmodel model) { if (isemailinuse(model.email) { // add modelstate error , return view } }
or catch exception when save (assuming data base field has unique constraint)
Comments
Post a Comment