Current state

This commit is contained in:
2026-02-07 08:23:18 +01:00
commit 0a4372c40d
22479 changed files with 1553543 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
requirejs.config({
baseUrl: '../',
paths: {
src: './src',
dist: './dist',
i18n: './src/i18n',
parsley: './src/parsley',
vendors: './bower_components'
},
map: {
'*': {
'jquery': 'vendors/jquery/jquery',
'validator': 'vendors/validator.js/dist/validator'
}
},
shim: {
'vendors/jquery/jquery': {
exports: '$'
},
'src/parsley': {
deps: ['jquery'],
exports: 'Parsley'
},
'src/parsley.remote': {
deps: ['jquery'],
exports: 'ParsleyExtend'
},
'vendors/validator.js/dist/validator': {
exports: 'Validator'
}
}
});

View File

@@ -0,0 +1,43 @@
// This plugin replace Parsley default form behavior that auto bind its fields children
// With this plugin you must register in constructor your form's fields and their constraints
// You have this way a total javascript control over your form validation, and nothing needed in DOM
window.ParsleyConfig = $.extend(true, window.ParsleyConfig, { autoBind: false });
window.ParsleyExtend = window.ParsleyExtend || {};
window.ParsleyExtend = $.extend(window.ParsleyExtend, {
// { '#selector' : { constraintName1: value, constraintName2: value2 }, #selector2: { constraintName: value } }
// { '#selector' : { constraintName1: { requirements: value, priority: value }, constraintName2: value2 } }
_bindFields: function () {
if ('ParsleyForm' !== this.__class__)
throw new Error('`_bindFields` must be called on a form instance');
if ('undefined' === typeof this.options.fields)
throw new Error('bind.js plugin needs to have Parsley instanciated with fields');
var field;
this.fields = [];
for (var selector in this.options.fields) {
if (0 === $(selector).length)
continue;
field = $(selector).parsley();
for (var name in this.options.fields[selector]) {
if ('object' === typeof this.options.fields[selector][name] && !(this.options.fields[selector][name] instanceof Array))
field.addConstraint(name.toLowerCase(), this.options.fields[selector][name].requirements, this.options.fields[selector][name].priority || 32);
else
field.addConstraint(name.toLowerCase(), this.options.fields[selector][name]);
}
}
this.fields.push(field);
return this;
},
// Do nothing
_bindConstraints: function () {
return this;
}
});

View File

@@ -0,0 +1,253 @@
// `window.ParsleyExtend`, like `ParsleyAbstract`, is inherited by `ParsleyField` and `ParsleyForm`
// That way, we could add new methods or redefine some for these both classes. In particular case
// We are adding async validation methods that returns promises, bind them properly to triggered
// Events like onkeyup when field is invalid or on form submit. These validation methods adds an
// Extra `remote` validator which could not be simply added like other `ParsleyExtra` validators
// Because returns promises instead of booleans.
window.ParsleyExtend = window.ParsleyExtend || {};
window.ParsleyExtend = $.extend(window.ParsleyExtend, {
asyncSupport: true,
asyncValidators: $.extend({
default: {
fn: function (xhr) {
return 'resolved' === xhr.state();
},
url: false
},
reverse: {
fn: function (xhr) {
// If reverse option is set, a failing ajax request is considered successful
return 'rejected' === xhr.state();
},
url: false
}
}, window.ParsleyExtend.asyncValidators),
addAsyncValidator: function (name, fn, url) {
this.asyncValidators[name.toLowerCase()] = {
fn: fn,
url: url || false
};
return this;
},
asyncValidate: function () {
if ('ParsleyForm' === this.__class__)
return this._asyncValidateForm.apply(this, arguments);
return this._asyncValidateField.apply(this, arguments);
},
asyncIsValid: function () {
if ('ParsleyField' === this.__class__)
return this._asyncIsValidField.apply(this, arguments);
return this._asyncIsValidForm.apply(this, arguments);
},
onSubmitValidate: function (event) {
var that = this;
// This is a Parsley generated submit event, do not validate, do not prevent, simply exit and keep normal behavior
if (true === event.parsley)
return;
// Clone the event object
this.submitEvent = $.extend(true, {}, event);
// Prevent form submit and immediately stop its event propagation
if (event instanceof $.Event) {
event.stopImmediatePropagation();
event.preventDefault();
}
return this._asyncValidateForm(undefined, event)
.done(function () {
// If user do not have prevented the event, re-submit form
if (!that.submitEvent.isDefaultPrevented())
that.$element.trigger($.extend($.Event('submit'), { parsley: true }));
});
},
eventValidate: function (event) {
// For keyup, keypress, keydown.. events that could be a little bit obstrusive
// do not validate if val length < min threshold on first validation. Once field have been validated once and info
// about success or failure have been displayed, always validate with this trigger to reflect every yalidation change.
if (new RegExp('key').test(event.type))
if (!this._ui.validationInformationVisible && this.getValue().length <= this.options.validationThreshold)
return;
this._ui.validatedOnce = true;
this.asyncValidate();
},
// Returns Promise
_asyncValidateForm: function (group, event) {
var
that = this,
promises = [];
this._refreshFields();
$.emit('parsley:form:validate', this);
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && group !== this.fields[i].options.group)
continue;
promises.push(this.fields[i]._asyncValidateField());
}
return $.when.apply($, promises)
.always(function () {
$.emit('parsley:form:validated', that);
});
},
_asyncIsValidForm: function (group, force) {
var promises = [];
this._refreshFields();
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && group !== this.fields[i].options.group)
continue;
promises.push(this.fields[i]._asyncIsValidField(force));
}
return $.when.apply($, promises);
},
_asyncValidateField: function (force) {
var that = this;
$.emit('parsley:field:validate', this);
return this._asyncIsValidField(force)
.done(function () {
$.emit('parsley:field:success', that);
})
.fail(function () {
$.emit('parsley:field:error', that);
})
.always(function () {
$.emit('parsley:field:validated', that);
});
},
_asyncIsValidField: function (force, value) {
var
deferred = $.Deferred(),
remoteConstraintIndex;
// If regular isValid (matching regular constraints) returns `false`, no need to go further
// Directly reject promise, do not run remote validator and save server load
if (false === this.isValid(force, value))
deferred.rejectWith(this);
// If regular constraints are valid, and there is a remote validator registered, run it
else if ('undefined' !== typeof this.constraintsByName.remote)
this._remote(deferred);
// Otherwise all is good, resolve promise
else
deferred.resolveWith(this);
// Return promise
return deferred.promise();
},
_remote: function (deferred) {
var
that = this,
data = {},
ajaxOptions,
csr,
validator = this.options.remoteValidator || (true === this.options.remoteReverse ? 'reverse' : 'default');
validator = validator.toLowerCase();
if ('undefined' === typeof this.asyncValidators[validator])
throw new Error('Calling an undefined async validator: `' + validator + '`');
// Fill data with current value
data[this.$element.attr('name') || this.$element.attr('id')] = this.getValue();
// All `$.ajax(options)` could be overridden or extended directly from DOM in `data-parsley-remote-options`
ajaxOptions = $.extend(true, {}, {
url: this.asyncValidators[validator].url || this.options.remote,
data: data,
type: 'GET'
}, this.options.remoteOptions || {});
// Generate store key based on ajax options
csr = $.param(ajaxOptions);
// Initialise querry cache
if ('undefined' === typeof this._remoteCache)
this._remoteCache = {};
// Try to retrieve stored xhr
if (!this._remoteCache[csr]) {
// Prevent multi burst xhr queries
if (this._xhr && 'pending' === this._xhr.state())
this._xhr.abort();
// Make ajax call
this._xhr = $.ajax(ajaxOptions)
// Store remote call result to avoid next calls with exact same parameters
this._remoteCache[csr] = this._xhr;
}
this._remoteCache[csr]
.done(function (data, textStatus, xhr) {
that._handleRemoteResult(validator, xhr, deferred);
})
.fail(function (xhr, status, message) {
// If we aborted the query, do not handle nothing for this value
if ('abort' === status)
return;
that._handleRemoteResult(validator, xhr, deferred);
});
},
_handleRemoteResult: function (validator, xhr, deferred) {
// If true, simply resolve and exit
if ('function' === typeof this.asyncValidators[validator].fn && this.asyncValidators[validator].fn(xhr)) {
deferred.resolveWith(this);
return;
}
// Else, create a proper remote validation Violation to trigger right UI
this.validationResult = [
new window.ParsleyValidator.Validator.Violation(
this.constraintsByName.remote,
this.getValue(),
null
)
];
deferred.rejectWith(this);
}
});
// Remote validator is just an always true sync validator with lowest (-1) priority possible
// It will be overloaded in `validateThroughValidator()` that will do the heavy async work
// This 'hack' is needed not to mess up too much with error messages and stuff in `ParsleyUI`
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.validators = window.ParsleyConfig.validators || {};
window.ParsleyConfig.validators.remote = {
fn: function () {
return true;
},
priority: -1
};

View File

@@ -0,0 +1,11 @@
// dateiso extra validator
// Guillaume Potier
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.validators = window.ParsleyConfig.validators || {};
window.ParsleyConfig.validators.dateiso = {
fn: function (value) {
return /^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])$/.test(value);
},
priority: 256
};

View File

@@ -0,0 +1,34 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.bg = $.extend(window.ParsleyConfig.i18n.bg || {}, {
defaultMessage: "Невалидна стойност.",
type: {
email: "Невалиден имейл адрес.",
url: "Невалиден URL адрес.",
number: "Невалиден номер.",
integer: "Невалиден номер.",
digits: "Невалидни цифри.",
alphanum: "Стойността трябва да садържа само букви или цифри."
},
notnull: "Полето е задължително.",
notblank: "Полето е задължително.",
required: "Полето е задължително.",
pattern: "Невалидна стойност.",
min: "Стойността трябва да бъде по-голяма или равна на %s.",
max: "Стойността трябва да бъде по-малка или равна на %s.",
range: "Стойността трябва да бъде между %s и %s.",
minlength: "Стойността е прекалено кратка. Мин. дължина: %s символа.",
maxlength: "Стойността е прекалено дълга. Макс. дължина: %s символа.",
length: "Дължината на стойността трябва да бъде между %s и %s символа.",
mincheck: "Трябва да изберете поне %s стойности.",
maxcheck: "Трябва да изберете най-много %s стойности.",
check: "Трябва да изберете между %s и %s стойности.",
equalto: "Стойността трябва да съвпада."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('bg', window.ParsleyConfig.i18n.bg, true);

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.da = $.extend(window.ParsleyConfig.i18n.da || {}, {
defaultMessage: "Indtast venligst en korrekt værdi.",
type: {
email: "Indtast venligst en korrekt email.",
url: "Indtast venligst en korrekt internetadresse.",
number: "Indtast venligst et korrekt nummer.",
integer: "Indtast venligst et korrekt tal.",
digits: "Dette felt må kun bestå af tal.",
alphanum: "Dette felt skal indeholde både tal og bogstaver."
},
notblank: "Dette felt må ikke være tomt.",
required: "Dette felt er påkrævet.",
pattern: "Ugyldig indtastning.",
min: "Dette felt skal indeholde mindst %s tegn.",
max: "Dette felt kan højest indeholde %s tegn.",
range: "Dette felt skal være mellem %s og %s tegn.",
minlength: "Indtast venligst mindst %s tegn.",
maxlength: "Dette felt kan kun indeholde %s tegn.",
length: "This value length is invalid. It should be between %s and %s characters long.",
mincheck: "Vælg mindst %s muligheder.",
maxcheck: "Vælg op til %s muligheder.",
check: "Vælg mellem %s og %s muligheder.",
equalto: "De to felter er ikke ens."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('da', window.ParsleyConfig.i18n.da, true);

View File

@@ -0,0 +1,30 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.de = $.extend(window.ParsleyConfig.i18n.de || {}, {
defaultMessage: "Die Eingabe scheint nicht korrekt zu sein.",
type: {
email: "Die Eingabe muss eine gültige E-Mail-Adresse sein.",
url: "Die Eingabe muss eine gültige URL sein.",
number: "Die Eingabe muss eine Zahl sein.",
integer: "Die Eingabe muss eine Zahl sein.",
digits: "Die Eingabe darf nur Ziffern enthalten.",
alphanum: "Die Eingabe muss alphanumerisch sein."
},
notblank: "Die Eingabe darf nicht leer sein.",
required: "Dies ist ein Pflichtfeld.",
pattern: "Die Eingabe scheint ungültig zu sein.",
min: "Die Eingabe muss größer oder gleich %s sein.",
max: "Die Eingabe muss kleiner oder gleich %s sein.",
range: "Die Eingabe muss zwischen %s und %s liegen.",
minlength: "Die Eingabe ist zu kurz. Es müssen mindestens %s Zeichen eingegeben werden.",
maxlength: "Die Eingabe ist zu lang. Es dürfen höchstens %s Zeichen eingegeben werden.",
length: "Die Länge der Eingabe ist ungültig. Es müssen zwischen %s und %s Zeichen eingegeben werden.",
equalto: "Dieses Feld muss dem anderen entsprechen."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('de', window.ParsleyConfig.i18n.de, true);

View File

@@ -0,0 +1,6 @@
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
window.ParsleyConfig.i18n.en = $.extend(window.ParsleyConfig.i18n.en || {}, {
dateiso: "This value should be a valid date (YYYY-MM-DD)."
});

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.en = $.extend(window.ParsleyConfig.i18n.en || {}, {
defaultMessage: "This value seems to be invalid.",
type: {
email: "This value should be a valid email.",
url: "This value should be a valid url.",
number: "This value should be a valid number.",
integer: "This value should be a valid integer.",
digits: "This value should be digits.",
alphanum: "This value should be alphanumeric."
},
notblank: "This value should not be blank.",
required: "This value is required.",
pattern: "This value seems to be invalid.",
min: "This value should be greater than or equal to %s.",
max: "This value should be lower than or equal to %s.",
range: "This value should be between %s and %s.",
minlength: "This value is too short. It should have %s characters or more.",
maxlength: "This value is too long. It should have %s characters or less.",
length: "This value length is invalid. It should be between %s and %s characters long.",
mincheck: "You must select at least %s choices.",
maxcheck: "You must select %s choices or less.",
check: "You must select between %s and %s choices.",
equalto: "This value should be the same."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('en', window.ParsleyConfig.i18n.en, true);

View File

@@ -0,0 +1,32 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
window.ParsleyConfig.i18n.es = $.extend(window.ParsleyConfig.i18n.es || {}, {
defaultMessage: "Este valor parece ser inválido.",
type: {
email: "Este valor debe ser un correo válido.",
url: "Este valor debe ser una URL válida.",
number: "Este valor debe ser un número válido.",
integer: "Este valor debe ser un número válido.",
digits: "Este valor debe ser un dígito válido.",
alphanum: "Este valor debe ser alfanumérico."
},
notblank: "Este valor no debe estar en blanco.",
required: "Este valor es requerido.",
pattern: "Este valor es incorrecto.",
min: "Este valor no debe ser menor que %s.",
max: "Este valor no debe ser mayor que %s.",
range: "Este valor debe estar entre %s y %s.",
minlength: "Este valor es muy corto. La longitud mínima es de %s caracteres.",
maxlength: "Este valor es muy largo. La longitud máxima es de %s caracteres.",
length: "La longitud de este valor debe estar entre %s y %s caracteres.",
mincheck: "Debe seleccionar al menos %s opciones.",
maxcheck: "Debe seleccionar %s opciones o menos.",
rangecheck: "Debe seleccionar entre %s y %s opciones.",
equalto: "Este valor debe ser idéntico."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('es', window.ParsleyConfig.i18n.es, true);

View File

@@ -0,0 +1,6 @@
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
window.ParsleyConfig.i18n.fr = $.extend(window.ParsleyConfig.i18n.fr || {}, {
dateiso: "Cette valeur n'est pas une date valide (YYYY-MM-DD)."
});

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.fr = $.extend(window.ParsleyConfig.i18n.fr || {}, {
defaultMessage: "Cette valeur semble non valide.",
type: {
email: "Cette valeur n'est pas une adresse email valide.",
url: "Cette valeur n'est pas une URL valide.",
number: "Cette valeur doit être un nombre.",
integer: "Cette valeur doit être un entier.",
digits: "Cette valeur doit être numérique.",
alphanum: "Cette valeur doit être alphanumérique."
},
notblank: "Cette valeur ne peut pas être vide.",
required: "Ce champ est requis.",
pattern: "Cette valeur semble non valide.",
min: "Cette valeur ne doit pas être inféreure à %s.",
max: "Cette valeur ne doit pas excéder %s.",
range: "Cette valeur doit être comprise entre %s et %s.",
minlength: "Cette chaîne est trop courte. Elle doit avoir au minimum %s caractères.",
maxlength: "Cette chaîne est trop longue. Elle doit avoir au maximum %s caractères.",
length: "Cette valeur doit contenir entre %s et %s caractères.",
mincheck: "Vous devez sélectionner au moins %s choix.",
maxcheck: "Vous devez sélectionner %s choix maximum.",
check: "Vous devez sélectionner entre %s et %s choix.",
equalto: "Cette valeur devrait être identique"
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('fr', window.ParsleyConfig.i18n.fr, true);

View File

@@ -0,0 +1,6 @@
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
window.ParsleyConfig.i18n.he = $.extend(window.ParsleyConfig.i18n.he || {}, {
dateiso: "ערך זה צריך להיות תאריך בפורמט (YYYY-MM-DD)."
});

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.he = $.extend(window.ParsleyConfig.i18n.he || {}, {
defaultMessage: "נראה כי ערך זה אינו תקף.",
type: {
email: "ערך זה צריך להיות כתובת אימייל.",
url: "ערך זה צריך להיות URL תקף.",
number: "ערך זה צריך להיות מספר.",
integer: "ערך זה צריך להיות מספר שלם.",
digits: "ערך זה צריך להיות ספרתי.",
alphanum: "ערך זה צריך להיות אלפאנומרי."
},
notblank: "ערך זה אינו יכול להשאר ריק.",
required: "ערך זה דרוש.",
pattern: "נראה כי ערך זה אינו תקף.",
min: "ערך זה צריך להיות לכל הפחות %s.",
max: "ערך זה צריך להיות לכל היותר %s.",
range: "ערך זה צריך להיות בין %s ל-%s.",
minlength: "ערך זה קצר מידי. הוא צריך להיות לכל הפחות %s תווים.",
maxlength: "ערך זה ארוך מידי. הוא צריך להיות לכל היותר %s תווים.",
length: "ערך זה אינו באורך תקף. האורך צריך להיות בין %s ל-%s תווים.",
mincheck: "אנא בחר לפחות %s אפשרויות.",
maxcheck: "אנא בחר לכל היותר %s אפשרויות.",
check: "אנא בחר בין %s ל-%s אפשרויות.",
equalto: "ערך זה צריך להיות זהה."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('he', window.ParsleyConfig.i18n.he, true);

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.id = $.extend(window.ParsleyConfig.i18n.id || {}, {
defaultMessage: "tidak valid",
type: {
email: "email tidak valid",
url: "url tidak valid",
number: "nomor tidak valid",
integer: "integer tidak valid",
digits: "harus berupa digit",
alphanum: "harus berupa alphanumeric"
},
notblank: "tidak boleh kosong",
required: "tidak boleh kosong",
pattern: "tidak valid",
min: "harus lebih besar atau sama dengan %s.",
max: "harus lebih kecil atau sama dengan %s.",
range: "harus dalam rentang %s dan %s.",
minlength: "terlalu pendek, minimal %s karakter atau lebih.",
maxlength: "terlalu panjang, maksimal %s karakter atau kurang.",
length: "panjang karakter harus dalam rentang %s dan %s",
mincheck: "pilih minimal %s pilihan",
maxcheck: "pilih maksimal %s pilihan",
check: "pilih antar %s dan %s pilihan",
equalto: "harus sama"
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('id', window.ParsleyConfig.i18n.id, true);

View File

@@ -0,0 +1,6 @@
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
window.ParsleyConfig.i18n.it = $.extend(window.ParsleyConfig.i18n.it || {}, {
dateiso: "Inserire una data valida (AAAA-MM-GG)."
});

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.it = $.extend(window.ParsleyConfig.i18n.it || {}, {
defaultMessage: "Questo valore sembra essere non valido.",
type: {
email: "Questo valore deve essere un indirizzo email valido.",
url: "Questo valore deve essere un URL valido.",
number: "Questo valore deve essere un numero valido.",
integer: "Questo valore deve essere un numero valido.",
digits: "Questo valore deve essere di tipo numerico.",
alphanum: "Questo valore deve essere di tipo alfanumerico."
},
notblank: "Questo valore non deve essere vuoto.",
required: "Questo valore è richiesto.",
pattern: "Questo valore non è corretto.",
min: "Questo valore deve essere maggiore di %s.",
max: "Questo valore deve essere minore di %s.",
range: "Questo valore deve essere compreso tra %s e %s.",
minlength: "Questo valore è troppo corto. La lunghezza minima è di %s caratteri.",
maxlength: "Questo valore è troppo lungo. La lunghezza massima è di %s caratteri.",
length: "La lunghezza di questo valore deve essere compresa fra %s e %s caratteri.",
mincheck: "Devi scegliere almeno %s opzioni.",
maxcheck: "Devi scegliere al più %s opzioni.",
check: "Devi scegliere tra %s e %s opzioni.",
equalto: "Questo valore deve essere identico."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('it', window.ParsleyConfig.i18n.it, true);

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.ja = $.extend(window.ParsleyConfig.i18n.ja || {}, {
defaultMessage: "無効な値です。",
type: {
email: "正しいメールアドレスを入力してください。",
url: "正しいURLを入力してください。",
number: "正しい数字を入力してください。",
integer: "正しい数値を入力してください。",
digits: "正しい桁数で入力してください。",
alphanum: "正しい英数字を入力してください。"
},
notblank: "この値を入力してください",
required: "この値は必須です。",
pattern: "この値は無効です。",
min: "%s 以上の値にしてください。",
max: "%s 以下の値にしてください。",
range: "%s から %s の値にしてください。",
minlength: "%s 文字以上で入力してください。",
maxlength: "%s 文字以下で入力してください。",
length: "%s から %s 文字の間で入力してください。",
mincheck: "%s 個以上選択してください。",
maxcheck: "%s 個以下選択してください。",
check: "%s から %s 個選択してください。",
equalto: "値が違います。"
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('ja', window.ParsleyConfig.i18n.ja, true);

View File

@@ -0,0 +1,40 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.nl = $.extend(window.ParsleyConfig.i18n.nl || {}, {
// parsley //////////////////////////////////////
defaultMessage: "Deze waarde lijkt onjuist."
, type: {
email: "Dit lijkt geen geldig e-mail adres te zijn."
, url: "Dit lijkt geen geldige URL te zijn."
, urlstrict: "Dit is geen geldige URL."
, number: "Deze waarde moet een nummer zijn."
, digits: "Deze waarde moet numeriek zijn."
, dateIso: "Deze waarde moet een datum in het volgende formaat zijn: (YYYY-MM-DD)."
, alphanum: "Deze waarde moet alfanumeriek zijn."
}
, notnull: "Deze waarde mag niet leeg zijn."
, notblank: "Deze waarde mag niet leeg zijn."
, required: "Dit veld is verplicht"
, regexp: "Deze waarde lijkt onjuist te zijn."
, min: "Deze waarde mag niet lager zijn dan %s."
, max: "Deze waarde mag niet groter zijn dan %s."
, range: "Deze waarde moet tussen %s en %s liggen."
, minlength: "Deze tekst is te kort. Deze moet uit minimaal %s karakters bestaan."
, maxlength: "Deze waarde is te lang. Deze mag maximaal %s karakters lang zijn."
, rangelength: "Deze waarde moet tussen %s en %s karakters lang zijn."
, equalto: "Deze waardes moeten identiek zijn."
// parsley.extend ///////////////////////////////
, minwords: "Deze waarde moet minstens %s woorden bevatten."
, maxwords: "Deze waarde mag maximaal %s woorden bevatten."
, rangewords: "Deze waarde moet tussen de %s en %s woorden bevatten."
, greaterthan: "Deze waarde moet groter dan %s zijn."
, lessthan: "Deze waarde moet kleiner dan %s zijn."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('nl', window.ParsleyConfig.i18n.nl, true);

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.pl = $.extend(window.ParsleyConfig.i18n.pl || {}, {
defaultMessage: "Wartość wygląda na nieprawidłową",
type: {
email: "Wpisz poprawny adres e-mail.",
url: "Wpisz poprawny adres URL.",
number: "Wpisz poprawną liczbę.",
integer: "Dozwolone jedynie liczby człkowite.",
digits: "Dozwolone jedynie cyfry.",
alphanum: "Dozwolone jedynie znaki alfanumeryczne."
},
notblank: "Pole nie może zostać puste",
required: "Pole jest wymagane.",
pattern: "Wartość wygląda na nieprawidłową.",
min: "Wartość powinna być większa od %s.",
max: "Wartość powinna być mniejsza od %s.",
range: "Wartość powinna być większa od %s i mniejsza od %s.",
minlength: "Ilość znaków powinna wynosić %s lub więcej.",
maxlength: "Ilość znaków powinna wynosić %s lub mniej.",
length: "Ilość znaków powinna wynosić od %s do %s.",
mincheck: "Musisz wybrać minimum %s opcji.",
maxcheck: "Możesz wybrać maksymalnie %s opcji.",
check: "Minimalnie możesz wybrać od %s do %s opcji",
equalto: "Wartości nie są identyczne"
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('pl', window.ParsleyConfig.i18n.pl, true);

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n['pt-br'] = $.extend(window.ParsleyConfig.i18n['pt-br'] || {}, {
defaultMessage: "This value seems to be invalid.",
type: {
email: "Esse campo deve ser um email válido.",
url: "Esse campo deve ser uma url válida.",
number: "Esse campo deve ser um número válido.",
integer: "Esse campo deve ser um inteiro válido.",
digits: "Esse campo deve conter apenas dígitos.",
alphanum: "Esse campo deve ser alfa numérico."
},
notblank: "Esse campo não pode ficar vazio.",
required: "Esse campo é obrigatório.",
pattern: "Esse campo parece estar inválido.",
min: "Esse campo deve ser maior ou igual a %s.",
max: "Esse campo deve ser menor ou igual a %s.",
range: "Esse campo deve estar entre %s e %s.",
minlength: "Esse campo é pequeno demais. Ele deveria ter %s characteres ou mais.",
maxlength: "Esse campo grande demais. Ele deveri ter %s characteres ou menos.",
length: "O tamanho desse campo é inválido. Ele deveria ter entre %s e %s characteres.",
mincheck: "Você deve escolher pelo menos %s opções.",
maxcheck: "Você deve escolher %s opções ou mais",
check: "Você deve escolher entre %s e %s opções.",
equalto: "Este valor deveria ser igual."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('pt-br', window.ParsleyConfig.i18n['pt-br'], true);

View File

@@ -0,0 +1,38 @@
//Parsley localization for Russian language
//Evgeni Makarov
//github.com/emakarov
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.ru = $.extend(window.ParsleyConfig.i18n.ru || {}, {
defaultMessage: "Некорректное значение.",
type: {
email: "Введите адрес электронной почты.",
url: "Введите URL адрес.",
number: "Введите число.",
integer: "Введите целое число.",
digits: "Введите только цифры.",
alphanum: "Введите буквенно-цифровое значение."
},
notblank: "Это поле должно быть заполнено.",
required: "Обязательное поле.",
pattern: "Это значение некорректно.",
min: "Это значение должно быть не менее чем %s.",
max: "Это значение должно быть не более чем %s.",
range: "Это значение должно быть в интервале от %s до %s.",
minlength: "Введите не менее %s символов.",
maxlength: "Введите не более %s символов.",
length: "Длина строки должна быть от %s до %s символов.",
mincheck: "Выберите не менее %s значений.",
maxcheck: "Выберите не более %s значений.",
check: "Выберите от %s до %s значений.",
equalto: "Это значение должно совпадать."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('ru', window.ParsleyConfig.i18n.ru, true);

View File

@@ -0,0 +1,6 @@
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
window.ParsleyConfig.i18n.sv = $.extend(window.ParsleyConfig.i18n.sv || {}, {
dateiso: "Ange ett giltigt datum (ÅÅÅÅ-MM-DD)."
});

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.sv = $.extend(window.ParsleyConfig.i18n.sv || {}, {
defaultMessage: "Ogiltigt värde.",
type: {
email: "Ange en giltig e-postadress.",
url: "Ange en giltig URL.",
number: "Ange ett giltigt nummer.",
integer: "Ange ett heltal.",
digits: "Ange endast siffror.",
alphanum: "Ange endast bokstäver och siffror."
},
notblank: "Värdet får inte vara tomt.",
required: "Måste fyllas i.",
pattern: "Värdet är ej giltigt.",
min: "Värdet måste vara större än eller lika med %s.",
max: "Värdet måste vara mindre än eller lika med %s.",
range: "Värdet måste vara mellan %s och %s.",
minlength: "Värdet måste vara minst %s tecken.",
maxlength: "Värdet får maximalt innehålla %s tecken.",
length: "Värdet måste vara mellan %s och %s tecken.",
mincheck: "Minst %s val måste göras.",
maxcheck: "Maximalt %s val får göras.",
check: "Mellan %s och %s val måste göras.",
equalto: "Värdena måste vara lika."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('sv', window.ParsleyConfig.i18n.sv, true);

View File

@@ -0,0 +1,6 @@
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
window.ParsleyConfig.i18n.zh_cn = $.extend(window.ParsleyConfig.i18n.zh_cn || {}, {
dateiso: "请输入正确格式的日期 (YYYY-MM-DD)."
});

View File

@@ -0,0 +1,33 @@
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.zh_cn = $.extend(window.ParsleyConfig.i18n.zh_cn || {}, {
defaultMessage: "不正确的值",
type: {
email: "请输入一个有效的电子邮箱地址",
url: "请输入一个有效的链接",
number: "请输入正确的数字",
integer: "请输入正确的整数",
digits: "请输入正确的号码",
alphanum: "请输入字母或数字"
},
notblank: "请输入值",
required: "必填项",
pattern: "格式不正确",
min: "输入值请大于或等于 %s",
max: "输入值请小于或等于 %s",
range: "输入值应该在 %s 到 %s 之间",
minlength: "请输入至少 %s 个字符",
maxlength: "请输入至多 %s 个字符",
length: "字符长度应该在 %s 到 %s 之间",
mincheck: "请至少选择 %s 个选项",
maxcheck: "请选择不超过 %s 个选项",
check: "请选择 %s 到 %s 个选项",
equalto: "输入值不同"
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('zh_cn', window.ParsleyConfig.i18n.zh_cn, true);

View File

@@ -0,0 +1,4 @@
require(['config'], function () {
require(['src/parsley'], function (Parsley) {
});
});

View File

@@ -0,0 +1,36 @@
input.parsley-success,
select.parsley-success,
textarea.parsley-success {
color: #468847;
background-color: #DFF0D8;
border: 1px solid #D6E9C6;
}
input.parsley-error,
select.parsley-error,
textarea.parsley-error {
color: #B94A48;
background-color: #F2DEDE;
border: 1px solid #EED3D7;
}
.parsley-errors-list {
margin: 2px 0 3px 0;
padding: 0;
list-style-type: none;
font-size: 0.9em;
line-height: 0.9em;
opacity: 0;
-moz-opacity: 0;
-webkit-opacity: 0;
transition: all .3s ease-in;
-o-transition: all .3s ease-in;
-ms-transition: all .3s ease-in-;
-moz-transition: all .3s ease-in;
-webkit-transition: all .3s ease-in;
}
.parsley-errors-list.filled {
opacity: 1;
}

View File

@@ -0,0 +1,10 @@
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.validators = window.ParsleyConfig.validators || {};
window.ParsleyConfig.validators.date = {
fn: function (value) {
return /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/.test(value);
},
priority: 256
};

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,69 @@
define('parsley/abstract', [
], function () {
var ParsleyAbstract = function() {};
ParsleyAbstract.prototype = {
asyncSupport: false,
actualizeOptions: function () {
this.options = this.OptionsFactory.get(this);
return this;
},
// ParsleyValidator validate proxy function . Could be replaced by third party scripts
validateThroughValidator: function (value, constraints, priority) {
return window.ParsleyValidator.validate.apply(window.ParsleyValidator, [value, constraints, priority]);
},
// Subscribe an event and a handler for a specific field or a specific form
// If on a ParsleyForm instance, it will be attached to form instance and also
// To every field instance for this form
subscribe: function (name, fn) {
$.listenTo(this, name.toLowerCase(), fn);
return this;
},
// Same as subscribe above. Unsubscribe an event for field, or form + its fields
unsubscribe: function (name) {
$.unsubscribeTo(this, name.toLowerCase());
return this;
},
// Reset UI
reset: function () {
// Field case: just emit a reset event for UI
if ('ParsleyForm' !== this.__class__)
return $.emit('parsley:field:reset', this);
// Form case: emit a reset event for each field
for (var i = 0; i < this.fields.length; i++)
$.emit('parsley:field:reset', this.fields[i]);
$.emit('parsley:form:reset', this);
},
// Destroy Parsley instance (+ UI)
destroy: function () {
// Field case: emit destroy event to clean UI and then destroy stored instance
if ('ParsleyForm' !== this.__class__) {
this.$element.removeData('Parsley');
this.$element.removeData('ParsleyFieldMultiple');
$.emit('parsley:field:destroy', this);
return;
}
// Form case: destroy all its fields and then destroy stored instance
for (var i = 0; i < this.fields.length; i++)
this.fields[i].destroy();
this.$element.removeData('Parsley');
$.emit('parsley:form:destroy', this);
}
};
return ParsleyAbstract;
});

View File

@@ -0,0 +1,55 @@
// All these options could be overriden and specified directly in DOM using
// `data-parsley-` default DOM-API
// eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"`
// eg: `data-parsley-stop-on-first-failing-constraint="false"`
define('parsley/defaults', function () {
return {
// ### General
// Default data-namespace for DOM API
namespace: 'data-parsley-',
// Supported inputs by default
inputs: 'input, textarea, select',
// Excluded inputs by default
excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden]',
// Stop validating field on highest priority failing constraint
priorityEnabled: true,
// ### UI
// Enable\Disable error messages
uiEnabled: true,
// Key events threshold before validation
validationThreshold: 3,
// Focused field on form validation error. 'fist'|'last'|'none'
focus: 'first',
// `$.Event()` that will trigger validation. eg: `keyup`, `change`..
trigger: false,
// Class that would be added on every failing validation Parsley field
errorClass: 'parsley-error',
// Same for success validation
successClass: 'parsley-success',
// Return the `$element` that will receive these above success or error classes
// Could also be (and given directly from DOM) a valid selector like `'#div'`
classHandler: function (ParsleyField) {},
// Return the `$element` where errors will be appended
// Could also be (and given directly from DOM) a valid selector like `'#div'`
errorsContainer: function (ParsleyField) {},
// ul elem that would receive errors' list
errorsWrapper: '<ul class="parsley-errors-list"></ul>',
// li elem that would receive error message
errorTemplate: '<li></li>'
};
});

View File

@@ -0,0 +1,36 @@
define('parsley/factory/constraint', [
'parsley/utils'
], function (ParsleyUtils) {
var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) {
if (!new RegExp('ParsleyField').test(ParsleyUtils.get(parsleyField, '__class__')))
throw new Error('ParsleyField or ParsleyFieldMultiple instance expected');
if ('function' !== typeof window.ParsleyValidator.validators[name] &&
'Assert' !== window.ParsleyValidator.validators[name](requirements).__parentClass__)
throw new Error('Valid validator expected');
var getPriority = function (parsleyField, name) {
if ('undefined' !== typeof parsleyField.options[name + 'Priority'])
return parsleyField.options[name + 'Priority'];
return ParsleyUtils.get(window.ParsleyValidator.validators[name](requirements), 'priority') || 2;
};
priority = priority || getPriority(parsleyField, name);
// If validator have a requirementsTransformer, execute it
if ('function' === typeof window.ParsleyValidator.validators[name](requirements).requirementsTransformer)
requirements = window.ParsleyValidator.validators[name](requirements).requirementsTransformer();
return $.extend(window.ParsleyValidator.validators[name](requirements), {
name: name,
requirements: requirements,
priority: priority,
groups: [priority],
isDomConstraint: isDomConstraint || ParsleyUtils.attr(parsleyField.$element, parsleyField.options.namespace, name)
});
};
return ConstraintFactory;
});

View File

@@ -0,0 +1,51 @@
define('parsley/factory/options', [
'parsley/utils'
], function (ParsleyUtils) {
var ParsleyOptionsFactory = function (defaultOptions, globalOptions, userOptions, namespace) {
this.__class__ = 'OptionsFactory';
this.__id__ = ParsleyUtils.hash(4);
this.formOptions = null;
this.fieldOptions = null;
this.staticOptions = $.extend(true, {}, defaultOptions, globalOptions, userOptions, { namespace: namespace });
};
ParsleyOptionsFactory.prototype = {
get: function (parsleyInstance) {
if ('undefined' === typeof parsleyInstance.__class__)
throw new Error('Parsley Instance expected');
switch (parsleyInstance.__class__) {
case 'Parsley':
return this.staticOptions;
case 'ParsleyForm':
return this.getFormOptions(parsleyInstance);
case 'ParsleyField':
case 'ParsleyFieldMultiple':
return this.getFieldOptions(parsleyInstance);
default:
throw new Error('Instance ' + parsleyInstance.__class__ + ' is not supported');
}
},
getFormOptions: function (formInstance) {
this.formOptions = ParsleyUtils.attr(formInstance.$element, this.staticOptions.namespace);
// not deep extend, since formOptions is a 1 level deep object
return $.extend({}, this.staticOptions, this.formOptions);
},
getFieldOptions: function (fieldInstance) {
this.fieldOptions = ParsleyUtils.attr(fieldInstance.$element, this.staticOptions.namespace);
if (null === this.formOptions && 'undefined' !== typeof fieldInstance.parent)
this.formOptions = this.getFormOptions(fieldInstance.parent);
// not deep extend, since formOptions and fieldOptions is a 1 level deep object
return $.extend({}, this.staticOptions, this.formOptions, this.fieldOptions);
}
};
return ParsleyOptionsFactory;
});

View File

@@ -0,0 +1,242 @@
define('parsley/field', [
'parsley/factory/constraint',
'parsley/ui',
'parsley/utils'
], function (ConstraintFactory, ParsleyUI, ParsleyUtils) {
var ParsleyField = function (field, OptionsFactory, parsleyFormInstance) {
this.__class__ = 'ParsleyField';
this.__id__ = ParsleyUtils.hash(4);
this.$element = $(field);
// If we have a parent `ParsleyForm` instance given, use its `OptionsFactory`, and save parent
if ('undefined' !== typeof parsleyFormInstance) {
this.parent = parsleyFormInstance;
this.OptionsFactory = this.parent.OptionsFactory;
this.options = this.OptionsFactory.get(this);
// Else, take the `Parsley` one
} else {
this.OptionsFactory = OptionsFactory;
this.options = this.OptionsFactory.get(this);
}
// Initialize some properties
this.constraints = [];
this.constraintsByName = {};
this.validationResult = [];
// Bind constraints
this._bindConstraints();
};
ParsleyField.prototype = {
// # Public API
// Validate field and $.emit some events for mainly `ParsleyUI`
// @returns validationResult:
// - `true` if all constraint passes
// - `[]` if not required field and empty (not validated)
// - `[Violation, [Violation..]]` if there were validation errors
validate: function (force) {
this.value = this.getValue();
// Field Validate event. `this.value` could be altered for custom needs
$.emit('parsley:field:validate', this);
$.emit('parsley:field:' + (this.isValid(force, this.value) ? 'success' : 'error'), this);
// Field validated event. `this.validationResult` could be altered for custom needs too
$.emit('parsley:field:validated', this);
return this.validationResult;
},
// Just validate field. Do not trigger any event
// Same @return as `validate()`
isValid: function (force, value) {
// Recompute options and rebind constraints to have latest changes
this.refreshConstraints();
// Sort priorities to validate more important first
var priorities = this._getConstraintsSortedPriorities();
// Value could be passed as argument, needed to add more power to 'parsley:field:validate'
value = value || this.getValue();
// If a field is empty and not required, leave it alone, it's just fine
// Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators
if (0 === value.length && !this._isRequired() && 'undefined' === typeof this.options.validateIfEmpty && true !== force)
return this.validationResult = [];
// If we want to validate field against all constraints, just call Validator and let it do the job
if (false === this.options.priorityEnabled)
return true === (this.validationResult = this.validateThroughValidator(value, this.constraints, 'Any'));
// Else, iterate over priorities one by one, and validate related asserts one by one
for (var i = 0; i < priorities.length; i++)
if (true !== (this.validationResult = this.validateThroughValidator(value, this.constraints, priorities[i])))
return false;
return true;
},
// @returns Parsley field computed value that could be overrided or configured in DOM
getValue: function () {
var value;
// Value could be overriden in DOM
if ('undefined' !== typeof this.options.value)
value = this.options.value;
else
value = this.$element.val();
// Handle wrong DOM or configurations
if ('undefined' === typeof value || null === value)
return '';
// Use `data-parsley-trim-value="true"` to auto trim inputs entry
if (true === this.options.trimValue)
return value.replace(/^\s+|\s+$/g, '');
return value;
},
// Actualize options that could have change since previous validation
// Re-bind accordingly constraints (could be some new, removed or updated)
refreshConstraints: function () {
return this.actualizeOptions()._bindConstraints();
},
/**
* Add a new constraint to a field
*
* @method addConstraint
* @param {String} name
* @param {Mixed} requirements optional
* @param {Number} priority optional
* @param {Boolean} isDomConstraint optional
*/
addConstraint: function (name, requirements, priority, isDomConstraint) {
name = name.toLowerCase();
if ('function' === typeof window.ParsleyValidator.validators[name]) {
var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint);
// if constraint already exist, delete it and push new version
if ('undefined' !== this.constraintsByName[constraint.name])
this.removeConstraint(constraint.name);
this.constraints.push(constraint);
this.constraintsByName[constraint.name] = constraint;
}
return this;
},
// Remove a constraint
removeConstraint: function (name) {
for (var i = 0; i < this.constraints.length; i++)
if (name === this.constraints[i].name) {
this.constraints.splice(i, 1);
break;
}
return this;
},
// Update a constraint (Remove + re-add)
updateConstraint: function (name, parameters, priority) {
return this.removeConstraint(name)
.addConstraint(name, parameters, priority);
},
// # Internals
// Internal only.
// Bind constraints from config + options + DOM
_bindConstraints: function () {
var constraints = [];
// clean all existing DOM constraints to only keep javascript user constraints
for (var i = 0; i < this.constraints.length; i++)
if (false === this.constraints[i].isDomConstraint)
constraints.push(this.constraints[i]);
this.constraints = constraints;
// then re-add Parsley DOM-API constraints
for (var name in this.options)
this.addConstraint(name, this.options[name]);
// finally, bind special HTML5 constraints
return this._bindHtml5Constraints();
},
// Internal only.
// Bind specific HTML5 constraints to be HTML5 compliant
_bindHtml5Constraints: function () {
// html5 required
if (this.$element.hasClass('required') || this.$element.attr('required'))
this.addConstraint('required', true, undefined, true);
// html5 pattern
if ('string' === typeof this.$element.attr('pattern'))
this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true);
// range
if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max'))
this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true);
// HTML5 min
else if ('undefined' !== typeof this.$element.attr('min'))
this.addConstraint('min', this.$element.attr('min'), undefined, true);
// HTML5 max
else if ('undefined' !== typeof this.$element.attr('max'))
this.addConstraint('max', this.$element.attr('max'), undefined, true);
// html5 types
var type = this.$element.attr('type');
if ('undefined' === typeof type)
return this;
// Small special case here for HTML5 number, that is in fact an integer validator
if ('number' === type)
return this.addConstraint('type', 'integer', undefined, true);
// Regular other HTML5 supported types
else if (new RegExp(type, 'i').test('email url range'))
return this.addConstraint('type', type, undefined, true);
return this;
},
// Internal only.
// Field is required if have required constraint without `false` value
_isRequired: function () {
if ('undefined' === typeof this.constraintsByName.required)
return false;
return false !== this.constraintsByName.required.requirements;
},
// Internal only.
// Sort constraints by priority DESC
_getConstraintsSortedPriorities: function () {
var priorities = [];
// Create array unique of priorities
for (var i = 0; i < this.constraints.length; i++)
if (-1 === priorities.indexOf(this.constraints[i].priority))
priorities.push(this.constraints[i].priority);
// Sort them by priority DESC
priorities.sort(function (a, b) { return b - a; });
return priorities;
}
};
return ParsleyField;
});

View File

@@ -0,0 +1,105 @@
define('parsley/form', [
'parsley/abstract',
'parsley/utils'
], function (ParsleyAbstract, ParsleyUtils) {
var ParsleyForm = function (element, OptionsFactory) {
this.__class__ = 'ParsleyForm';
this.__id__ = ParsleyUtils.hash(4);
if ('OptionsFactory' !== ParsleyUtils.get(OptionsFactory, '__class__'))
throw new Error('You must give an OptionsFactory instance');
this.OptionsFactory = OptionsFactory;
this.$element = $(element);
this.validationResult = null;
this.options = this.OptionsFactory.get(this);
};
ParsleyForm.prototype = {
onSubmitValidate: function (event) {
this.validate(undefined, undefined, event);
// prevent form submission if validation fails
if (false === this.validationResult && event instanceof $.Event) {
event.stopImmediatePropagation();
event.preventDefault();
}
return this;
},
// @returns boolean
validate: function (group, force, event) {
this.submitEvent = event;
this.validationResult = true;
var fieldValidationResult = [];
// Refresh form DOM options and form's fields that could have changed
this._refreshFields();
$.emit('parsley:form:validate', this);
// loop through fields to validate them one by one
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && group !== this.fields[i].options.group)
continue;
fieldValidationResult = this.fields[i].validate(force);
if (true !== fieldValidationResult && fieldValidationResult.length > 0 && this.validationResult)
this.validationResult = false;
}
$.emit('parsley:form:validated', this);
return this.validationResult;
},
// Iterate over refreshed fields, and stop on first failure
isValid: function (group, force) {
this._refreshFields();
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && group !== this.fields[i].options.group)
continue;
if (false === this.fields[i].isValid(force))
return false;
}
return true;
},
_refreshFields: function () {
return this.actualizeOptions()._bindFields();
},
_bindFields: function () {
var self = this;
this.fields = [];
this.fieldsMappedById = {};
this.$element.find(this.options.inputs).each(function () {
var fieldInstance = new window.Parsley(this, {}, self);
// Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children
if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && !fieldInstance.$element.is(fieldInstance.options.excluded))
if ('undefined' === typeof self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) {
self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance;
self.fields.push(fieldInstance);
}
});
return this;
}
};
return ParsleyForm;
});

View File

@@ -0,0 +1,77 @@
define('parsley/multiple', [
], function () {
var ParsleyMultiple = function () {
this.__class__ = 'ParsleyFieldMultiple';
};
ParsleyMultiple.prototype = {
// Add new `$element` sibling for multiple field
addElement: function ($element) {
this.$elements.push($element);
return this;
},
// See `ParsleyField.refreshConstraints()`
refreshConstraints: function () {
var fieldConstraints;
this.constraints = [];
// Select multiple special treatment
if (this.$element.is('select')) {
this.actualizeOptions()._bindConstraints();
return this;
}
// Gather all constraints for each input in the multiple group
for (var i = 0; i < this.$elements.length; i++) {
fieldConstraints = this.$elements[i].data('ParsleyFieldMultiple').refreshConstraints().constraints;
for (var j = 0; j < fieldConstraints.length; j++)
this.addConstraint(fieldConstraints[j].name, fieldConstraints[j].requirements, fieldConstraints[j].priority, fieldConstraints[j].isDomConstraint);
}
return this;
},
// See `ParsleyField.getValue()`
getValue: function () {
// Value could be overriden in DOM
if ('undefined' !== typeof this.options.value)
return this.options.value;
// Radio input case
if (this.$element.is('input[type=radio]'))
return $('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').val() || '';
// checkbox input case
if (this.$element.is('input[type=checkbox]')) {
var values = [];
$('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').each(function () {
values.push($(this).val());
});
return values.length ? values : [];
}
// Select multiple case
if (this.$element.is('select') && null === this.$element.val())
return [];
// Default case that should never happen
return this.$element.val();
},
_init: function (multiple) {
this.$elements = [this.$element];
this.options.multiple = multiple;
return this;
}
};
return ParsleyMultiple;
});

View File

@@ -0,0 +1,103 @@
define('parsley/pubsub', [
'parsley/field',
'parsley/form'
], function (ParsleyField, ParsleyForm) {
var
o = $({}),
subscribed = {};
// $.listen(name, callback);
// $.listen(name, context, callback);
$.listen = function (name) {
if ('undefined' === typeof subscribed[name])
subscribed[name] = [];
if ('function' === typeof arguments[1])
return subscribed[name].push({ fn: arguments[1] });
if ('object' === typeof arguments[1] && 'function' === typeof arguments[2])
return subscribed[name].push({ fn: arguments[2], ctxt: arguments[1] });
throw new Error('Wrong parameters');
};
$.listenTo = function (instance, name, fn) {
if ('undefined' === typeof subscribed[name])
subscribed[name] = [];
if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm))
throw new Error('Must give Parsley instance');
if ('string' !== typeof name || 'function' !== typeof fn)
throw new Error('Wrong parameters');
subscribed[name].push({ instance: instance, fn: fn });
};
$.unsubscribe = function (name, fn) {
if ('undefined' === typeof subscribed[name])
return;
if ('string' !== typeof name || 'function' !== typeof fn)
throw new Error('Wrong arguments');
for (var i = 0; i < subscribed[name].length; i++)
if (subscribed[name][i].fn === fn)
return subscribed[name].splice(i, 1);
};
$.unsubscribeTo = function (instance, name) {
if ('undefined' === typeof subscribed[name])
return;
if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm))
throw new Error('Must give Parsley instance');
for (var i = 0; i < subscribed[name].length; i++)
if ('undefined' !== typeof subscribed[name][i].instance && subscribed[name][i].instance.__id__ === instance.__id__)
return subscribed[name].splice(i, 1);
};
$.unsubscribeAll = function (name) {
if ('undefined' === typeof subscribed[name])
return;
delete subscribed[name];
};
// $.emit(name [, arguments...]);
// $.emit(name, instance [, arguments..]);
$.emit = function (name, instance) {
if ('undefined' === typeof subscribed[name])
return;
// loop through registered callbacks for this event
for (var i = 0; i < subscribed[name].length; i++) {
// if instance is not registered, simple emit
if ('undefined' === typeof subscribed[name][i].instance) {
subscribed[name][i].fn.apply('undefined' !== typeof subscribed[name][i].ctxt ? subscribed[name][i].ctxt : o, Array.prototype.slice.call(arguments, 1));
continue;
}
// if instance registered but no instance given for the emit, continue
if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm))
continue;
// if instance is registered and same id, emit
if (subscribed[name][i].instance.__id__ === instance.__id__) {
subscribed[name][i].fn.apply(o, Array.prototype.slice.call(arguments, 1));
continue;
}
// if registered instance is a Form and fired one is a Field, loop over all its fields and emit if field found
if (subscribed[name][i].instance instanceof ParsleyForm && instance instanceof ParsleyField)
for (var j = 0; j < subscribed[name][i].instance.fields.length; j++)
if (subscribed[name][i].instance.fields[j].__id__ === instance.__id__) {
subscribed[name][i].fn.apply(o, Array.prototype.slice.call(arguments, 1));
continue;
}
}
};
$.subscribed = function () { return subscribed; };
});

View File

@@ -0,0 +1,409 @@
define('parsley/ui', [
'parsley/utils'
], function (ParsleyUtils) {
var ParsleyUI = function (options) {
this.__class__ = 'ParsleyUI';
};
ParsleyUI.prototype = {
listen: function () {
$.listen('parsley:form:init', this, this.setupForm);
$.listen('parsley:field:init', this, this.setupField);
$.listen('parsley:field:validated', this, this.reflow);
$.listen('parsley:form:validated', this, this.focus);
$.listen('parsley:field:reset', this, this.reset);
$.listen('parsley:form:destroy', this, this.destroy);
$.listen('parsley:field:destroy', this, this.destroy);
return this;
},
reflow: function (fieldInstance) {
// If this field has not an active UI (case for multiples) don't bother doing something
if ('undefined' === typeof fieldInstance._ui || false === fieldInstance._ui.active)
return;
// Diff between two validation results
var diff = this._diff(fieldInstance.validationResult, fieldInstance._ui.lastValidationResult);
// Then store current validation result for next reflow
fieldInstance._ui.lastValidationResult = fieldInstance.validationResult;
// Field have been validated at least once if here. Useful for binded key events..
fieldInstance._ui.validatedOnce = true;
// Handle valid / invalid / none field class
this.manageStatusClass(fieldInstance);
// Add, remove, updated errors messages
this.manageErrorsMessages(fieldInstance, diff);
// Triggers impl
this.actualizeTriggers(fieldInstance);
// If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user
if ((diff.kept.length || diff.added.length) && 'undefined' === typeof fieldInstance._ui.failedOnce)
this.manageFailingFieldTrigger(fieldInstance);
},
// Returns an array of field's error message(s)
getErrorsMessages: function (fieldInstance) {
// No error message, field is valid
if (true === fieldInstance.validationResult)
return [];
var messages = [];
for (var i = 0; i < fieldInstance.validationResult.length; i++)
messages.push(this._getErrorMessage(fieldInstance, fieldInstance.validationResult[i].assert));
return messages;
},
manageStatusClass: function (fieldInstance) {
if (true === fieldInstance.validationResult)
this._successClass(fieldInstance);
else if (fieldInstance.validationResult.length > 0)
this._errorClass(fieldInstance);
else
this._resetClass(fieldInstance);
},
manageErrorsMessages: function (fieldInstance, diff) {
if ('undefined' !== typeof fieldInstance.options.errorsMessagesDisabled)
return;
// Case where we have errorMessage option that configure an unique field error message, regardless failing validators
if ('undefined' !== typeof fieldInstance.options.errorMessage) {
if ((diff.added.length || diff.kept.length)) {
if (0 === fieldInstance._ui.$errorsWrapper.find('.parsley-custom-error-message').length)
fieldInstance._ui.$errorsWrapper
.append($(fieldInstance.options.errorTemplate)
.addClass('parsley-custom-error-message'));
return fieldInstance._ui.$errorsWrapper
.addClass('filled')
.find('.parsley-custom-error-message')
.html(fieldInstance.options.errorMessage);
}
return fieldInstance._ui.$errorsWrapper
.removeClass('filled')
.find('.parsley-custom-error-message')
.remove();
}
// Show, hide, update failing constraints messages
for (var i = 0; i < diff.removed.length; i++)
this.removeError(fieldInstance, diff.removed[i].assert.name, true);
for (i = 0; i < diff.added.length; i++)
this.addError(fieldInstance, diff.added[i].assert.name, undefined, diff.added[i].assert, true);
for (i = 0; i < diff.kept.length; i++)
this.updateError(fieldInstance, diff.kept[i].assert.name, undefined, diff.kept[i].assert, true);
},
// TODO: strange API here, intuitive for manual usage with addError(pslyInstance, 'foo', 'bar')
// but a little bit complex for above internal usage, with forced undefined parametter..
addError: function (fieldInstance, name, message, assert, doNotUpdateClass) {
fieldInstance._ui.$errorsWrapper
.addClass('filled')
.append($(fieldInstance.options.errorTemplate)
.addClass('parsley-' + name)
.html(message || this._getErrorMessage(fieldInstance, assert)));
if (true !== doNotUpdateClass)
this._errorClass(fieldInstance);
},
// Same as above
updateError: function (fieldInstance, name, message, assert, doNotUpdateClass) {
fieldInstance._ui.$errorsWrapper
.addClass('filled')
.find('.parsley-' + name)
.html(message || this._getErrorMessage(fieldInstance, assert));
if (true !== doNotUpdateClass)
this._errorClass(fieldInstance);
},
// Same as above twice
removeError: function (fieldInstance, name, doNotUpdateClass) {
fieldInstance._ui.$errorsWrapper
.removeClass('filled')
.find('.parsley-' + name)
.remove();
// edge case possible here: remove a standard Parsley error that is still failing in fieldInstance.validationResult
// but highly improbable cuz' manually removing a well Parsley handled error makes no sense.
if (true !== doNotUpdateClass)
this.manageStatusClass(fieldInstance);
},
focus: function (formInstance) {
if (true === formInstance.validationResult || 'none' === formInstance.options.focus)
return formInstance._focusedField = null;
formInstance._focusedField = null;
for (var i = 0; i < formInstance.fields.length; i++)
if (true !== formInstance.fields[i].validationResult && formInstance.fields[i].validationResult.length > 0 && 'undefined' === typeof formInstance.fields[i].options.noFocus) {
if ('first' === formInstance.options.focus) {
formInstance._focusedField = formInstance.fields[i].$element;
return formInstance._focusedField.focus();
}
formInstance._focusedField = formInstance.fields[i].$element;
}
if (null === formInstance._focusedField)
return null;
return formInstance._focusedField.focus();
},
_getErrorMessage: function (fieldInstance, constraint) {
var customConstraintErrorMessage = constraint.name + 'Message';
if ('undefined' !== typeof fieldInstance.options[customConstraintErrorMessage])
return window.ParsleyValidator.formatMessage(fieldInstance.options[customConstraintErrorMessage], constraint.requirements);
return window.ParsleyValidator.getErrorMessage(constraint);
},
_diff: function (newResult, oldResult, deep) {
var
added = [],
kept = [];
for (var i = 0; i < newResult.length; i++) {
var found = false;
for (var j = 0; j < oldResult.length; j++)
if (newResult[i].assert.name === oldResult[j].assert.name) {
found = true;
break;
}
if (found)
kept.push(newResult[i]);
else
added.push(newResult[i]);
}
return {
kept: kept,
added: added,
removed: !deep ? this._diff(oldResult, newResult, true).added : []
};
},
setupForm: function (formInstance) {
formInstance.$element.on('submit.Parsley', false, $.proxy(formInstance.onSubmitValidate, formInstance));
// UI could be disabled
if (false === formInstance.options.uiEnabled)
return;
formInstance.$element.attr('novalidate', '');
},
setupField: function (fieldInstance) {
var _ui = { active: false };
// UI could be disabled
if (false === fieldInstance.options.uiEnabled)
return;
_ui.active = true;
// Give field its Parsley id in DOM
fieldInstance.$element.attr(fieldInstance.options.namespace + 'id', fieldInstance.__id__);
/** Generate important UI elements and store them in fieldInstance **/
// $errorClassHandler is the $element that woul have parsley-error and parsley-success classes
_ui.$errorClassHandler = this._manageClassHandler(fieldInstance);
// $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer
_ui.errorsWrapperId = 'parsley-id-' + ('undefined' !== typeof fieldInstance.options.multiple ? 'multiple-' + fieldInstance.options.multiple : fieldInstance.__id__);
_ui.$errorsWrapper = $(fieldInstance.options.errorsWrapper).attr('id', _ui.errorsWrapperId);
// ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly
_ui.lastValidationResult = [];
_ui.validatedOnce = false;
_ui.validationInformationVisible = false;
// Store it in fieldInstance for later
fieldInstance._ui = _ui;
/** Mess with DOM now **/
this._insertErrorWrapper(fieldInstance);
// Bind triggers first time
this.actualizeTriggers(fieldInstance);
},
// Determine which element will have `parsley-error` and `parsley-success` classes
_manageClassHandler: function (fieldInstance) {
// An element selector could be passed through DOM with `data-parsley-class-handler=#foo`
if ('string' === typeof fieldInstance.options.classHandler && $(fieldInstance.options.classHandler).length)
return $(fieldInstance.options.classHandler);
// Class handled could also be determined by function given in Parsley options
var $handler = fieldInstance.options.classHandler(fieldInstance);
// If this function returned a valid existing DOM element, go for it
if ('undefined' !== typeof $handler && $handler.length)
return $handler;
// Otherwise, if simple element (input, texatrea, select..) it will perfectly host the classes
if ('undefined' === typeof fieldInstance.options.multiple || fieldInstance.$element.is('select'))
return fieldInstance.$element;
// But if multiple element (radio, checkbox), that would be their parent
return fieldInstance.$element.parent();
},
_insertErrorWrapper: function (fieldInstance) {
var $errorsContainer;
if ('string' === typeof fieldInstance.options.errorsContainer )
if ($(fieldInstance.options.errorsContainer + '').length)
return $(fieldInstance.options.errorsContainer).append(fieldInstance._ui.$errorsWrapper);
else if (window.console && window.console.warn)
window.console.warn('The errors container `' + fieldInstance.options.errorsContainer + '` does not exist in DOM');
if ('function' === typeof fieldInstance.options.errorsContainer)
$errorsContainer = fieldInstance.options.errorsContainer(fieldInstance);
if ('undefined' !== typeof $errorsContainer && $errorsContainer.length)
return $errorsContainer.append(fieldInstance._ui.$errorsWrapper);
return 'undefined' === typeof fieldInstance.options.multiple ? fieldInstance.$element.after(fieldInstance._ui.$errorsWrapper) : fieldInstance.$element.parent().after(fieldInstance._ui.$errorsWrapper);
},
actualizeTriggers: function (fieldInstance) {
var that = this;
// Remove Parsley events already binded on this field
if (fieldInstance.options.multiple)
$('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () {
$(this).off('.Parsley');
});
else
fieldInstance.$element.off('.Parsley');
// If no trigger is set, all good
if (false === fieldInstance.options.trigger)
return;
var triggers = fieldInstance.options.trigger.replace(/^\s+/g , '').replace(/\s+$/g , '');
if ('' === triggers)
return;
// Bind fieldInstance.eventValidate if exists (for parsley.ajax for example), ParsleyUI.eventValidate otherwise
if (fieldInstance.options.multiple)
$('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () {
$(this).on(
triggers.split(' ').join('.Parsley ') + '.Parsley',
false,
$.proxy('function' === typeof fieldInstance.eventValidate ? fieldInstance.eventValidate : that.eventValidate, fieldInstance));
});
else
fieldInstance.$element
.on(
triggers.split(' ').join('.Parsley ') + '.Parsley',
false,
$.proxy('function' === typeof fieldInstance.eventValidate ? fieldInstance.eventValidate : this.eventValidate, fieldInstance));
},
// Called through $.proxy with fieldInstance. `this` context is ParsleyField
eventValidate: function(event) {
// For keyup, keypress, keydown.. events that could be a little bit obstrusive
// do not validate if val length < min threshold on first validation. Once field have been validated once and info
// about success or failure have been displayed, always validate with this trigger to reflect every yalidation change.
if (new RegExp('key').test(event.type))
if (!this._ui.validationInformationVisible && this.getValue().length <= this.options.validationThreshold)
return;
this._ui.validatedOnce = true;
this.validate();
},
manageFailingFieldTrigger: function (fieldInstance) {
fieldInstance._ui.failedOnce = true;
// Radio and checkboxes fields must bind every field multiple
if (fieldInstance.options.multiple)
$('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () {
if (!new RegExp('change', 'i').test($(this).parsley().options.trigger || ''))
return $(this).on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance));
});
// Select case
if (fieldInstance.$element.is('select'))
if (!new RegExp('change', 'i').test(fieldInstance.options.trigger || ''))
return fieldInstance.$element.on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance));
// All other inputs fields
if (!new RegExp('keyup', 'i').test(fieldInstance.options.trigger || ''))
return fieldInstance.$element.on('keyup.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance));
},
reset: function (parsleyInstance) {
// Reset all event listeners
parsleyInstance.$element.off('.Parsley');
parsleyInstance.$element.off('.ParsleyFailedOnce');
// Nothing to do if UI never initialized for this field
if ('undefined' === typeof parsleyInstance._ui)
return;
if ('ParsleyForm' === parsleyInstance.__class__)
return;
// Reset all errors' li
parsleyInstance._ui.$errorsWrapper.children().each(function () {
$(this).remove();
});
// Reset validation class
this._resetClass(parsleyInstance);
// Reset validation flags and last validation result
parsleyInstance._ui.validatedOnce = false;
parsleyInstance._ui.lastValidationResult = [];
parsleyInstance._ui.validationInformationVisible = false;
},
destroy: function (parsleyInstance) {
this.reset(parsleyInstance);
if ('ParsleyForm' === parsleyInstance.__class__)
return;
parsleyInstance._ui.$errorsWrapper.remove();
delete parsleyInstance._ui;
},
_successClass: function (fieldInstance) {
fieldInstance._ui.validationInformationVisible = true;
fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.errorClass).addClass(fieldInstance.options.successClass);
},
_errorClass: function (fieldInstance) {
fieldInstance._ui.validationInformationVisible = true;
fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).addClass(fieldInstance.options.errorClass);
},
_resetClass: function (fieldInstance) {
fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).removeClass(fieldInstance.options.errorClass);
}
};
return ParsleyUI;
});

View File

@@ -0,0 +1,95 @@
define('parsley/utils', function () {
return {
// Parsley DOM-API
// returns object from dom attributes and values
// if attr is given, returns bool if attr present in DOM or not
attr: function ($element, namespace, checkAttr) {
var
attribute,
obj = {},
regex = new RegExp('^' + namespace, 'i');
if ('undefined' === typeof $element || 'undefined' === typeof $element[0])
return {};
for (var i in $element[0].attributes) {
attribute = $element[0].attributes[i];
if ('undefined' !== typeof attribute && null !== attribute && attribute.specified && regex.test(attribute.name)) {
if ('undefined' !== typeof checkAttr && new RegExp(checkAttr + '$', 'i').test(attribute.name))
return true;
obj[this.camelize(attribute.name.replace(namespace, ''))] = this.deserializeValue(attribute.value);
}
}
return 'undefined' === typeof checkAttr ? obj : false;
},
setAttr: function ($element, namespace, attr, value) {
$element[0].setAttribute(this.dasherize(namespace + attr), String(value));
},
// Recursive object / array getter
get: function (obj, path) {
var
i = 0,
paths = (path || '').split('.');
while (this.isObject(obj) || this.isArray(obj)) {
obj = obj[paths[i++]];
if (i === paths.length)
return obj;
}
return undefined;
},
hash: function (length) {
return String(Math.random()).substring(2, length ? length + 2 : 9);
},
/** Third party functions **/
// Underscore isArray
isArray: function (mixed) {
return Object.prototype.toString.call(mixed) === '[object Array]';
},
// Underscore isObject
isObject: function (mixed) {
return mixed === Object(mixed);
},
// Zepto deserialize function
deserializeValue: function (value) {
var num;
try {
return value ?
value == "true" ||
(value == "false" ? false :
value == "null" ? null :
!isNaN(num = Number(value)) ? num :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value)
: value;
} catch (e) { return value; }
},
// Zepto camelize function
camelize: function (str) {
return str.replace(/-+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
},
// Zepto dasherize function
dasherize: function (str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase();
}
};
});

View File

@@ -0,0 +1,222 @@
define('parsley/validator', [
'validator'
], function (Validator) {
var ParsleyValidator = function (validators, catalog) {
this.__class__ = 'ParsleyValidator';
this.Validator = Validator;
// Default Parsley locale is en
this.locale = 'en';
this.init(validators || {}, catalog || {});
};
ParsleyValidator.prototype = {
init: function (validators, catalog) {
this.catalog = catalog;
for (var name in validators)
this.addValidator(name, validators[name].fn, validators[name].priority);
$.emit('parsley:validator:init');
},
// Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n
setLocale: function (locale) {
if ('undefined' === typeof this.catalog[locale])
throw new Error(locale + ' is not available in the catalog');
this.locale = locale;
return this;
},
// Add a new messages catalog for a given locale. Set locale for this catalog if set === `true`
addCatalog: function (locale, messages, set) {
if ('object' === typeof messages)
this.catalog[locale] = messages;
if (true === set)
return this.setLocale(locale);
return this;
},
// Add a specific message for a given constraint in a given locale
addMessage: function (locale, name, message) {
if (undefined === typeof this.catalog[locale])
this.catalog[locale] = {};
this.catalog[locale][name.toLowerCase()] = message;
return this;
},
validate: function (value, constraints, priority) {
return new this.Validator.Validator().validate.apply(new Validator.Validator(), arguments);
},
// Add a new validator
addValidator: function (name, fn, priority) {
this.validators[name.toLowerCase()] = function (requirements) {
return $.extend(new Validator.Assert().Callback(fn, requirements), { priority: priority });
};
return this;
},
updateValidator: function (name, fn, priority) {
return addValidator(name, fn, priority);
},
removeValidator: function (name) {
delete this.validators[name];
return this;
},
getErrorMessage: function (constraint) {
var message;
// Type constraints are a bit different, we have to match their requirements too to find right error message
if ('type' === constraint.name)
message = this.catalog[this.locale][constraint.name][constraint.requirements];
else
message = this.formatMessage(this.catalog[this.locale][constraint.name], constraint.requirements);
return '' !== message ? message : this.catalog[this.locale].defaultMessage;
},
// Kind of light `sprintf()` implementation
formatMessage: function (string, parameters) {
if ('object' === typeof parameters) {
for (var i in parameters)
string = this.formatMessage(string, parameters[i]);
return string;
}
return 'string' === typeof string ? string.replace(new RegExp('%s', 'i'), parameters) : '';
},
// Here is the Parsley default validators list.
// This is basically Validatorjs validators, with different API for some of them
// and a Parsley priority set
validators: {
notblank: function () {
return $.extend(new Validator.Assert().NotBlank(), { priority: 2 });
},
required: function () {
return $.extend(new Validator.Assert().Required(), { priority: 512 });
},
type: function (type) {
var assert;
switch (type) {
case 'email':
assert = new Validator.Assert().Email();
break;
case 'number':
assert = new Validator.Assert().Regexp('^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$');
break;
case 'integer':
assert = new Validator.Assert().Regexp('^-?\\d+$');
break;
case 'digits':
assert = new Validator.Assert().Regexp('^\\d+$');
break;
case 'alphanum':
assert = new Validator.Assert().Regexp('^\\w+$', 'i');
break;
case 'url':
assert = new Validator.Assert().Regexp('(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)', 'i');
break;
default:
throw new Error('validator type `' + type + '` is not supported');
}
return $.extend(assert, { priority: 256 });
},
pattern: function (regexp) {
var flags = '';
// Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
if (!!(/^\/.*\/(?:[gimy]*)$/.test(regexp))) {
// Replace the regexp literal string with the first match group: ([gimy]*)
// If no flag is present, this will be a blank string
flags = regexp.replace(/.*\/([gimy]*)$/, '$1');
// Again, replace the regexp literal string with the first match group:
// everything excluding the opening and closing slashes and the flags
regexp = regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
}
return $.extend(new Validator.Assert().Regexp(regexp, flags), { priority: 64 });
},
minlength: function (value) {
return $.extend(new Validator.Assert().Length({ min: value }), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
maxlength: function (value) {
return $.extend(new Validator.Assert().Length({ max: value }), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
length: function (array) {
return $.extend(new Validator.Assert().Length({ min: array[0], max: array[1] }), { priority: 32 });
},
mincheck: function (length) {
return this.minlength(length);
},
maxcheck: function (length) {
return this.maxlength(length);
},
check: function (array) {
return this.length(array);
},
min: function (value) {
return $.extend(new Validator.Assert().GreaterThanOrEqual(value), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
max: function (value) {
return $.extend(new Validator.Assert().LessThanOrEqual(value), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
range: function (array) {
return $.extend(new Validator.Assert().Range(array[0], array[1]), {
priority: 32,
requirementsTransformer: function () {
for (var i = 0; i < array.length; i++)
array[i] = 'string' === typeof array[i] && !isNaN(array[i]) ? parseInt(array[i], 10) : array[i];
return array;
}
});
},
equalto: function (value) {
return $.extend(new Validator.Assert().EqualTo(value), {
priority: 256,
requirementsTransformer: function () {
return $(value).length ? $(value).val() : value;
}
});
}
}
};
return ParsleyValidator;
});

View File

@@ -0,0 +1,6 @@
// AMD Compliance
if ('function' === typeof define && define.amd)
define('parsley', function() { return window.Parsley; } );
})(window.jQuery);

View File

@@ -0,0 +1,9 @@
/*!
* @@name
* @@author
* Version @@version - built @@timestamp
* @@license Licensed
*
*/
!(function($) {