Here i will explain how to create custom and conditional server side and client side validation like required-if in asp.net core.
In above image if shutter type checkbox is checked then min height and max height filed is required.This scenario would be handled by conditional validation in asp.net core mvc.
Implement custom validation for server side and client side validation.
public class RequiredIFAttribute:ValidationAttribute, IClientModelValidator
{
public string PropertyName { get; set; }
public RequiredIFAttribute(string propertyName,string errorMessage="")
{
PropertyName = propertyName;
ErrorMessage =errorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var instance = validationContext.ObjectInstance;
var type=instance.GetType();
var pType = type.GetProperty(PropertyName).PropertyType;
var pValue = type.GetProperty(PropertyName).GetValue(instance, null);
if (pType == typeof(string) && !string.IsNullOrWhiteSpace(Convert.ToString(pValue)) && value==null)
{
ErrorMessage= string.IsNullOrEmpty(ErrorMessage) ? string.Concat(validationContext.DisplayName, " is required.") : ErrorMessage;
return new ValidationResult(ErrorMessage);
}
else if (pType == typeof(bool) && Convert.ToBoolean(pValue) == true && value == null)
{
ErrorMessage = string.IsNullOrEmpty(ErrorMessage) ? string.Concat(validationContext.DisplayName, " is required.") : ErrorMessage;
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
string error = string.IsNullOrEmpty(ErrorMessage) ? string.Concat(context.ModelMetadata.DisplayName, " required.") : ErrorMessage;
if(!context.Attributes.ContainsKey("data-val"))
context.Attributes.Add("data-val", "true");
context.Attributes.Add("data-val-requiredif", error);
context.Attributes.Add("data-val-requiredif-refproperty",PropertyName);
}
To implement client side validation use below code
$.validator.addMethod('requiredif', function (value, element, params) {
const comparePropertyName = params.refproperty;
const compareProperty = $(element).closest('form').find('[name="' + comparePropertyName + '"]');
const comparePropertyType = compareProperty.attr('type');
if (comparePropertyType === 'checkbox') {
if (compareProperty.is(':checked') && value !== null && value !== '')
return true;
}
else {
const comparePropertyValue = compareProperty.val();
if ((comparePropertyValue === 'True' && value !== null && value !== '') || comparePropertyValue === 'False')
return true;
}
return false;
});
$.validator.unobtrusive.adapters.add('requiredif', ["refproperty"], function (options) {
options.rules['requiredif'] = options.params;
options.messages['requiredif'] = options.message;
});
paste this javascript code on your page or in js file that is called on this page.
To use this code can implement Custom and Conditional validation in asp.net core mvc.
RequiredIF validation in dotnet core mvc.