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?