0

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

2
  • Put your question on top of the question may make more readable. Commented Feb 26, 2020 at 12:31
  • For the client-side validation to work, you need to set the attribute data-val="true" on the field where you want validation and also the correct error message using data-val-requiredStrings="Your error message". Can't see it anywhere in your code above. Commented Feb 26, 2020 at 15:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.