Search code examples
javascript.net-coredata-annotations

Validation message is not displaying for custom attribute in .Net Core


I am creating custom attribut for validation to override RegularExpressionAttribute in .Net Core, and Implemented IClientModelValidator for client side validation. validation is apply on field but didn't display Error message for it. ModelState.IsValid is also giving Invalid that field but validation message is not displaying.

ViewModel

[Required]
[Display(Name = "First Name")]
[RestrictSplCharacters]
public string FirstName { get; set; }

Override Attribute

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class RestrictSplCharactersAttribute : RegularExpressionAttribute, IClientModelValidator
{
   private string errorMessage= "Special characters or blank space is not allowed in {0}";

public RestrictSplCharactersAttribute()
    : base(@"[_A-z0-9]*((-|\s)*[_A-z0-9])*$")
{
    this.ErrorMessage = this.errorMessage;
}

public void AddValidation(ClientModelValidationContext context)
{
    MergeAttribute(context.Attributes, "data-val", "true");
    var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
    MergeAttribute(context.Attributes, "data-val-restrictSplCharacters", errorMessage);
}

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

In Html Control is like

<div class="oneditshow">
<input autocomplete="off" class="k-textbox valid k-valid" data-val="true" data-val-required="The First Name field is required." data-val-restrictSplCharacters="Special characters or blank space is not allowed in First Name" id="FirstName" name="FirstName" placeholder="First Name" required="required" style="width: 100%" value="" aria-required="true" aria-describedby="FirstName-error">
<span class="text-danger field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true" style="display: none;"></span>
   </div>

Javascript function

<script>

    var $jQval = $.validator;

    $jQval.addMethod("restrictSplCharacters",
        function (value, element, parameters) {
            var regExp = "/[_A-z0-9]*((-|\s)*[_A-z0-9])*$/";
            if (value.match(regExp)) {
                return true;
            } else {
                return false;
            }
        });
    var adapters = $jQval.unobtrusive.adapters;
    adapters.addBool("restrictSplCharacters");
</script>

Solution

  • Thank you, Client Side validation is not fired because it's kendo UI. I replace my JavaScript with Below javascript for kendo custom validation Rule.

        //register custom validation rules
    (function ($, kendo) {
        $.extend(true, kendo.ui.validator, {
            rules: { // custom rules
                restrictSpecialCharacters: function (input, params) {
                    //check for the rule attribute 
                    if (input.filter("[data-val-restrictSpecialCharacters]").length && input.val()) {
                        return /[_A-z0-9]*((-|\s)*[_A-z0-9])*$/.test(input.val());
                    }
                    return true;
                }
            },
            messages: { //custom rules messages
                restrictSpecialCharacters: function (input) {
                    // return the message text
                    return input.attr("data-val-restrictSpecialCharacters");
                }
            }
        });
    })(jQuery, kendo);