I have an ASP.NET MVC 4 application and I'd like to have unobtrusive validation for several properties of the view model. Here's a simplified version :
ViewModel :
[AtLeastOne(new[] {"FirstName", "LastName"})]
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Validation attribute :
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AtLeastOneAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _propertyNames;
public AtLeastOneAttribute(string[] propertyNames)
{
if (propertyNames == null) throw new ArgumentNullException("propertyNames");
if (propertyNames.Length < 2) throw new ArgumentOutOfRangeException("propertyNames");
_propertyNames = propertyNames;
}
public override bool IsValid(object value)
{
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var modelClientValidationRule = new ModelClientValidationRule
{
ErrorMessage = "AAAAA!!!",
ValidationType = "atleastone",
};
modelClientValidationRule.ValidationParameters.Add(new KeyValuePair<string, object>("propertynames", _propertyNames));
return new[]
{
modelClientValidationRule
};
}
}
Although I have :
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
in Web.config and
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
jQuery.validator.unobtrusive.adapters.add("atleastone", ['FirstName', 'LastName'], function (options) {
alert('options!');
});
</script>
set in my view nothing is rendered for this validation. If I, for example, add [Required] for FirstName or LastName, data-* validation attributes are added.
How can I achieve this multi-property custom client-side validation?
WANT TO SEE / DOWNLOAD THE WHOLE SOLUTION?
AtLeastOneAttribute
has the[AttributeUsage]
attribute? – haim770jQuery.validator.unobtrusive.add("atleastone")
? – haim770