1

I'm struggling to figure out an issue with a custom validation attribute and why this is not acting the same as a non-custom validation attribute.

I've setup a really basic custom validation attribute as an example:

public class AlwaysFalse : ValidationAttribute, IClientValidatable
{
    public IEnumerable<ModelClientValidationRule> 
GetClientValidationRules(ModelMetadata metadata, ControllerContext 
context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "alwaysfalse"
        };
    }

    protected override ValidationResult IsValid(object value, 
ValidationContext validationContext)
    {
        return new ValidationResult("Error");
    }
}

I've applied the attribute to a property in my Model.

The custom js I have written is as follows:

jQuery.validator.addMethod('falseMethod', function (value, element, 
params) {
        return false;
}, '');

// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('alwaysfalse', {}, function 
(options) {
    options.rules['falseMethod'] = true;
options.messages['falseMethod'] = options.message;
});

I have followed the advice from the following post: Perform client side validation for custom attribute

When I call my Controllers POST function, the validation occurs fine. However I want it to be triggered similar to other validationAttributes. For example, i've also setup a Range validation Attribute on one of my models properties and as soon as I enter invalid information into this field, the class "input-validation-error" is assigned to the input field in question.

Any help/assistance would be greatly appreciated.

Please let me know if I can provide more information.

1 Answers1

0

Ok, now answered this.

I'm quite new to C# and didn't realise the difference between have asp.NET core as my target framework and trying to use a .Net class.

I also had warnings surrounding the Web.MVC class not working as expected.

The forum post resolved my issue: ASP.Net Core MVC - Client-side validation for custom attribute

Changed to using IClientModelValidator class using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;