I am trying to implement client side validation in MVC 3 over Unobtrusive AJAX form.
public class PhoneNumberAttribute : RegularExpressionAttribute, IClientValidatable
{
private const string Message = " must be a valid phone number";
public PhoneNumberAttribute()
: base(@"^[\s\d\+\(\)]+$")
{
ErrorMessage = "{0}" + Message;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
return new List<ModelClientValidationRule>() {
new ModelClientValidationRule{
ValidationType="phonenumber",
ErrorMessage= metadata.DisplayName + " " + Message
}
};
}
}
Model:
public class MyModel
{
[DisplayName("Phone Number")]
[PhoneNumber]
public string PhoneNumber{ get; set; }
}
HTML
<% using (Ajax.BeginForm("Contact", new AjaxOptions() { UpdateTargetId = "ajaxcontactform",
OnBegin = "ShowProcessing",
OnComplete = "HideProessing",
InsertionMode = InsertionMode.Replace
}))
{%>
<%: Html.ValidationSummary()%>
<%: Html.TextBoxFor(m => m.PhoneNumber, new { Class = "contacttextform" })%>
<input id="sendBtn" name="send" type="submit" class="contactformbutton" value="Send" />
<%}%>
I have included required .js files and other client side validation works for the fields which have [Required] attribute as well as custom validation attribute.
Please suggest why its not working for PhoneNumber field?
Thanks,
the C# code is only one side of the validation. all your doing there is defining meta data to perform the validation against. You also need to register the validation with unobtrusive JavaScript, in JavaScript, see
Unobtrusive validation of collection
and
http://odetocode.com/Blogs/scott/archive/2011/02/22/custom-data-annotation-validator-part-ii-client-code.aspx
Edit
Having looked at it I’m wondering if your over thinking this. I don’t see why you need the
IClientValidatableat all as all your doing is inheriting fromRegularExpressionAttribute, try the below: