Custom Server and Client Side Validation in Asp.net Core

Author : Sachin Sharma
Published On : 31 Mar 2023

In this article we will discuss about custom validation in dotnet core for both server and client side.

Here we will create a custom validation to check file extension.

public class FileExtensionAttribute:ValidationAttribute, IClientModelValidator
    {
        public string Extensions { get; set; }
        public FileExtensionAttribute(string extensions)
        {
            Extensions = extensions;

        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if(value !=null)
            {
                var file = (IFormFile)value;
               if(!Extensions.Contains(Path.GetExtension(file.FileName)))
                {
                    ErrorMessage = string.IsNullOrEmpty(ErrorMessage) ? string.Concat(validationContext.DisplayName, " invalid file extension.") : 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, " invalid file extension.") : ErrorMessage;

            if (!context.Attributes.ContainsKey("data-val"))
                context.Attributes.Add("data-val", "true");

                context.Attributes.Add("data-val-fileextension",error);
            context.Attributes.Add("data-val-fileextension-validtypes", Extensions);
        }        
    }

Inherit ValidationAttribute used to implement server validation and override IsValid method.

Inherit IClientModelValidator used to implement unobtrusive client side validation to implement AddValidation method.

now uses  FileExtensionAttribute in model class

 
public class FileUploadModel

{

  [FileExtension(".png,.gif")]
  public IFormFile File { get; set; }
}

$(function(){
$.validator.addMethod('fileextension', function (value, element, params) {    
    var selectedFileType = value.split('.').pop();       
    var validFileTypes = params.validtypes;    
    return (validFileTypes.toLowerCase().indexOf(selectedFileType.toLowerCase()) !== -1);
});

$.validator.unobtrusive.adapters.add('fileextension', ['validtypes'], function (options) {
    options.rules['fileextension'] = options.params;
    options.messages['fileextension'] = options.message;
});
});

call these function on view page where extension used.

Now the rendered html would be like 

 

validation1/

 

validation2/

Comments

No comments have been added to this article.

Add Comment