IsValid method is not working in custom required validation attribute in MVC and i am not using ModelState.IsValid

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x