Parsley is the validation script we use for our forms. Its official documentation can be found here.
How to Create a Custom Validation Message
When you have a special type of field, Parsley allows error messages for the field being required and formatted to match the type.
All field types get data-parsley-type-message regardless of the field’s type. Replace <type> with email, number, date, etc.
<input type="<type>" name="" data-parsley-type="<type>" data-parsley-required="true" data-parsley-type-message="invalid type error message" data-parsley-required-message="required missing error message">
Custom File Validators
These validators allow you to validate with PArsley the file type being upload and set a max size for the upload.
This example will validate for PDF, Word Documents, and Text/Rich Text documents (for a resume upload or something).
How To
Script
Add this into the scripts.js near the rest of the custom parsley validation.
var app = app || {};
// Utils
(function ($, app) {
'use strict';
app.utils = {};
app.utils.formDataSuppoerted = (function () {
return !!('FormData' in window);
}());
}(jQuery, app));
window.Parsley.addValidator('filemaxmegabytes', {
requirementType: 'string',
validateString: function (value, requirement, parsleyInstance) {
if (!app.utils.formDataSuppoerted) {
return true;
}
var file = parsleyInstance.$element[0].files;
var maxBytes = requirement * 1048576;
if (file.length == 0) {
return true;
}
return file.length === 1 && file[0].size <= maxBytes;
},
messages: {
en: 'File is to big'
}
});
window.Parsley.addValidator('filemimetypes', {
requirementType: 'string',
validateString: function (value, requirement, parsleyInstance) {
if (!app.utils.formDataSuppoerted) {
return true;
}
var file = parsleyInstance.$element[0].files;
if (file.length == 0) {
return true;
}
var allowedMimeTypes = requirement.replace(/\s/g, "").split(',');
return allowedMimeTypes.indexOf(file[0].type) !== -1;
},
messages: {
en: 'File mime type not allowed'
}
});
HTML
This is an example input field to show what it will look like.
<input type="file" name="fileUpload" id="uploadAFile" accept="application/pdf|application/msword|text/rtf" class="inputfile" data-parsley-filemaxmegabytes="2" data-parsley-trigger="change" data-parsley-filemimetypes="application/pdf, application/msword, text/rtf, text"> <label for="uploadAFile" class="btn btn-default">Choose a file</label></div>
Tags: bs3, bs4, parsley, form