Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>
like image 722
JIgsB Avatar asked Nov 26 '18 10:11

JIgsB


People also ask

How do I create a custom validation in .NET core?

Validation attributes let you specify validation rules for model properties. We can create custom validation attributes, create a class that inherits from ValidationAttribute, and override the IsValid method. Here is the code. The IsValid method accepts an object named value, which is the input to be validated.

How do I create a custom validation attribute?

To create a custom validation attributeUnder Add New Item, click Class. In the Name box, enter the name of the custom validation attribute class. You can use any name that is not already being used. For example, you can enter the name CustomAttribute.

What is ModelState in ASP net Core?

Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field.


2 Answers

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);
like image 86
JIgsB Avatar answered Sep 30 '22 17:09

JIgsB


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.

like image 23
Karan Avatar answered Sep 30 '22 18:09

Karan