5

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>
JIgsB
  • 143
  • 6
  • 1
    if you're using tooltip for displaying error message then add an id with name `FirstName-error` to span ``. – Curiousdev Nov 26 '18 at 11:38
  • My view is like @(Html.Kendo().TextBoxFor(model => model.FirstName) .Value("") .HtmlAttributes(new { style = "width: 100%", placeholder = "First Name", autocomplete = "off", required = "required" }) .Deferred()) @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" }) – JIgsB Nov 26 '18 at 11:51
  • 1
    Ok i think you need to add custom rules in kendo validator please find [this link](https://www.telerik.com/blogs/extending-the-kendo-ui-validator-with-custom-rules) for more info... – Curiousdev Nov 26 '18 at 12:11

2 Answers2

3

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);
JIgsB
  • 143
  • 6
1

Try with adding following code after public void AddValidation in RestrictSpecialCharactersAttribute.

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    ModelClientValidationRule mvr = new ModelClientValidationRule();
    mvr.ErrorMessage = this.eRRORMESSAGE;
    mvr.ValidationType = "restrictSpecialCharacters";
    return new[] { mvr };
}

You can find more details here.

Karan
  • 12,059
  • 3
  • 24
  • 40