1

I have a model like

public class Employee
{
    [Required]
    [RegularExpression]
    public string Name { get; set; }
}

When I type spaces in the textbox then required field validation is not firing (though I keep the AllowEmptyString property of Required validation).

I have written a custom validation and planned to override IsValid() as below:

[AttributeUsage(AttributeTargets.Property)]
public class CustomRequiredValidatiorAttribute : ValidationAttribute, IClientValidatable
{
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metaData, ControllerContext context)
    {
        if (metaData == null)
        {
            throw new ArgumentNullException(nameof(metaData));
        }

        var rule = new ModelClientValidationRule
            {
                ErrorMessage = "Error msg",
            };

        rule.ValidationType = "required";
        rule.ValidationParameters["propertynames"] = metaData.PropertyName;

        yield return rule;
    }

    public override bool IsValid(object value)
    {
        // some logic
    }
}  

and model looks like

public class Employee
{
    [CustomRequiredValidatiorAttribute]
    [RegularExpression]
    public string Name { get; set; }
}

In my code, this validation should fire without page refresh/postback

But IsValid() is not being called, could someone help me how to fix this issue?

  • Does this answer help https://stackoverflow.com/a/39146892/8715436 or this https://stackoverflow.com/a/29043225/8715436? – E. Shcherbo Oct 19 '20 at 08:37

1 Answers1

0

Since I am not posting the page to the server IsValid() won't fire