Shadam
Shadam

Reputation: 1122

JQuery custom validation attribute MVC core

I try to add a custom attribute to validate required field and trim value for white space.

So here is my custom attribute :

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class CustomRequired : ValidationAttribute, IClientModelValidator
{
    public CustomRequired()
    {
        ErrorMessage = new ResourceManager(typeof(ErrorResource)).GetString("All_Required");
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));

        MergeAttribute(context.Attributes, "data-val", "true");
        MergeAttribute(context.Attributes, "data-val-customrequired", ErrorMessage);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        return value.ToString().Trim().Length > 0 ? ValidationResult.Success : new ValidationResult(ErrorMessage);
    }

    private static bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
}

And here how I add it (or try) :

$(document).ready(function () {
    $.validator.addMethod("customrequired", function (value, element, parameters) {
        return $.trim(value).length > 0;
    });
    $.validator.unobtrusive.adapters.addBool('customrequired');
});

And set it on property in a viewmodel :

[CustomRequired]
public string Code { get; set; }

My problem is it doesn't had any client side validation whereas the function is in the jQuery validator... The ModelState is invalid so the controller reject it but I want a client side validation.

console:

enter image description here

enter image description here

Edit :

I forgot to say I'm using kendo... See my own answer below.

Upvotes: 2

Views: 683

Answers (1)

Shadam
Shadam

Reputation: 1122

I forgot to say that I'm using kendo...

My code is functional with a classic validation but not with kendo edit pop-up. :/

So here is the solution for those who have the same problem, write this in your javascript instead of add it in the $.validator :

(function ($, kendo) {
    $.extend(true, kendo.ui.validator, {
        rules: {
            customrequired: function (input) {
                if (input.is("[data-val-customrequired]")) {
                    return $.trim(input.val()).length > 0;
                }
                return true;
            }
        },
        messages: {
            customrequired: function (input) {
                return input.attr("data-val-customrequired");
            }
        }
    });
})(jQuery, kendo);

Upvotes: 1

Related Questions