Search code examples
ruby-on-rails-3fileclient-side-validation

Client side validation of file type


I have a form and there I wanna allow to user upload only one type of file. I use client side validation, but the file-type validation has not behavior as I would expected. I tried to validation the file type with these two ways:

  validates :doc_type, :allow_blank => true, :format => {:with => /\A.*\.(pdf|PDF)\z/, :message => 'must be PDF file.'}

and also

validates_attachment_content_type :doc_type, :content_type => { :content_type => "application/pdf" }

But the error about bad file type is not displayed via Client side validation, but as usual validation error.

Exist any way to display the validation error by Client side validation?


Solution

  • I suggest using the jquery validate plugin on the client side first, before submitting to your back end. This allows you to validate file types on the front end.

    http://docs.jquery.com/Plugins/Validation/Methods/accept

    Here is a sample, makes "field" required and ending with ".xls" or ".csv".

    $("#myform").validate({
      rules: {
        field: {
          required: true,
          accept: "xls|csv"
        }
      }
    });
    

    The great thing about using the jquery validation plugin is that it will also make other ciient side validations convenient, like email, password, etc.