0

I am new to data annotations, so i am trying to get it working. The predefined data annotations like [Required] and [RegularExpression] are working perfectly, however, when i try to add a custom class validation, it is completely ignored. Here's my source code:

namespace Models
{
    public class ModelClass
    {
        [Display(Name = "Test")]
        [CustomClassTest]
        public int? TestIntField { get; set; }
    }
    public class CustomClassTest : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationcontext)
        {
            return new ValidationResult("Work please");
        }
    }
}

ClientValidationEnabled is true, as well as UnobtrusiveJavascriptEnabled. What am i doing wrong here?

EDIT

Apparently, the custom validation class works fine on submitting the form, however, when the focus on the field is lost, the validation message does not appear (unlike other data annotations like [required]). Is there a way to show the validation error on focus lost?

  • weird, everything looks right. Have you added the `using System.ComponentModel.DataAnnotations` – Rajshekar Reddy Sep 23 '16 at 07:26
  • Well, yes. It would have thrown an error otherwise, wouldn't it? Besides, all the other data annotations work fine, as is said. – Alexander Rykunov Sep 23 '16 at 07:38
  • 1
    So when you say your validator is not working, Do you mean when you submit the form the validation is not triggered? Can you check in your action result if your `ModelState.IsValid` is true? – Rajshekar Reddy Sep 23 '16 at 07:47
  • Hav a look at [this](http://stackoverflow.com/questions/19726404/client-side-validation-in-custom-validation-attribute-asp-net-mvc-4) SO question. – Jeroen Heier Sep 23 '16 at 07:49
  • Apparently custom validation class works on submitting the form, i completely missed that. However, i want validation message to appear on focus of the field lost. As far as i know, it is a default behaviour, isnt it? Updated the OP post. – Alexander Rykunov Sep 23 '16 at 08:04
  • @Alexander "it is a default behaviour, isnt it?" yes it is default behavior but only predefined validation rules which are already available in jquery.validate.unobtrusive.js like required, email etc. Any custom validation attribute that you are adding at server side needs to be add at client side if you need to be work that validation at client side also. To get clear idea refer this simple example http://www.ezzylearning.com/tutorial/creating-custom-validation-attribute-in-asp-net-mvc – Hemant D Sep 23 '16 at 09:59

0 Answers0