Do you have any examples of how a client validation for a string[] should look like?
I have the following custom validator class, which is working fine on the server side:
public class RequiredRepeatedStrings : ValidationAttribute, IClientValidatable
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string[] valueAsStringArray = value as string[];
if (valueAsStringArray == null || valueAsStringArray.Any(x => string.IsNullOrEmpty(x)))
return new ValidationResult(this.ErrorMessage);
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metaData, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metaData.GetDisplayName());
rule.ValidationType = "requiredStrings";
yield return rule;
}
}
My Model:
[RequiredRepeatedStrings(ErrorMessage = "Bitte eine Anschrift eingeben!")]
[Display(Name = "Anschrift")]
public string[] Address { get; set; }
The Partial-View (somewhere in the foreach loop):
@foreach (var country in Model.CompanyLocations.SelectedCountry)
{
...
<div class="form-group add_top_60">
@Html.LabelFor(m => m.CompanyLocations.Address):
@Html.TextBoxFor(m => m.CompanyLocations.Address[index], new { placeholder = "Max-Mustermann Str. 1", @class = "form-control" })
<i class="icon_mail_alt" style="top: 32px;"></i>
@Html.ValidationMessageFor(m => m.CompanyLocations.Address, null, new { @class = "text-danger" })
</div>
...
}
The JS adapter:
$.validator.unobtrusive.adapters.add("requiredStrings");
$.validator.addMethod("requiredStrings", function (value, element, params) {
for (var i = 0; i < value.length; i++) {
if (value[i] == '') {
return false;
}
}
return true;
});
But the client side validation is not working this case. The references are already included and the client side validation for a custom validator works in other cases like "if the input value contains special characters". So it is not because of the references to the libraries and so on. Something with the code seems to not work properly.
The scenaraio is, I have a form in which I can add additional locations and each location has for instance a street name. The street name is therefore a string array. If the input field is empty it is not null but ''.
Any ideas?
I already checked this post, but there is no solution there: Validate String Array In ASP.NET MVC in client side
Thanks
Dee
data-val="true"on the field where you want validation and also the correct error message usingdata-val-requiredStrings="Your error message". Can't see it anywhere in your code above.