fValidator for mootools 1.2
Abstract
fValidator is an open source (free), unobtrusive javascript tool for easy handling form validation, written by Fabio Zendhi Nagao (http://zend.lojcomm.com.br). Fabio’s fabulous formvalidating script is now updated for use with MooTools 1.2. Also added a few extra validators, and the script is now multilingual!
New features
- Mootools 1.2 compatible
- Validators for
- EU-date format
- ISO-8601 date format
- Multi-language support
- English
- Dutch
Usage
Initialize the fValidator class like you are used to:
var myValidator = new fValidator("formId");
Or, try a different language:
var myValidator = new fValidator("formId", {language: "nl"});
The language configuration is found in the options section of the fValidator Class and easy to modify. See an example:
languageConfig: { en: { required: "This field is required.", alpha: "This field accepts alphabetic characters only.", alphanum: "This field accepts alphanumeric characters only.", integer: "Please enter a valid integer.", real: "Please enter a valid number.", date: "Please enter a valid date (mm/dd/yyyy).", dateISO8601:"Please enter a valid date (yyyy-mm-dd).", dateEU: "Please enter a valid date (mm-dd-yyyy).", email: "Please enter a valid email.", phone: "Please enter a valid phone.", url: "Please enter a valid url.", confirm: "Confirm Password does not match original Password." }, nl: { required: "Dit veld is verplicht.", alpha: "U kunt in dit veld alleen karakters uit het alphabet invoeren.", alphanum: "U kunt in dit veld alleen alphanumerieke karakters invoeren.", integer: "Voer een geheel getal in.", real: "Voer een getal in.", date: "Voer een geldige datum in (mm/dd/yyyy).", dateISO8601:"Voer een geldige datum in (yyyy-mm-dd).", dateEU: "Voer een geldige datum in (mm-dd-yyyy).", email: "Voer een geldig emailadres in.", phone: "Voer een geldig telefoonnummer in.", url: "Voer een geldige url in.", confirm: "Het bevestigingswachtwoord komt niet overeen met het originele wachtwoord." } }
Feel free to send in your own translations!
Downloads
Download fValidator for MooTools 1.2 here: fValidator1.2.js
You can get MooTools here: http://mootools.net/download
The original version of fValidator (including examples) is found here: http://zendold.lojcomm.com.br/fvalidator/
Y have make an in Italian and spanish validation here it is:
it: { required: "Questo campo è obbligatorio.",
alpha: "Questo campo accetta solo lettere.",
alphanum: "Questo campo accetta solo caratteri alfanumerici.",
integer: "Per favore inserisca un valido numero intero.",
real: "Per favore inserisca un numero valido.",
date: "Per favore inserisca una data in formato valido (mm/gg/aaaa).",
dateISO8601:"Per favore inserisca una data in formato valido (aaaa-mm-gg).",
dateEU: "Per favore inserisca una data in formato valido (mm-gg-aaaa).",
email: "Per favore inserisca una email valida.",
phone: "Per favore inserisca un telefono valido.",
url: "Per favore inserisca un indirizzo internet valido.",
zip: "Per favore inserisca un codice postale valido.",
confirm: "La password di controllo non è uguale alla password originale."
},
es: { required: "Este campo es un campo obligatorio.",
alpha: "Este campo acepta solo letteras.",
alphanum: "Este campo acepta solo caracteres alfanuméricos.",
integer: "Este campo acepta solo números enteros.",
real: "Este campo acepta únicamente caracteres numéricos.",
date: "Por favor inserte una fetcha en formato valido (mm/dd/aaaa).",
dateISO8601:"Por favor inserte una fetcha en formato valido (aaaa-mm-dd).",
dateEU: "Por favor inserte una fetcha en formato valido (mm-dd-aaaa).",
email: "Por favor inserte un correo electrónico valido.",
phone: "Por favor inserte un numero de teléfono valido.",
url: "Por favor inserte una direcíon de internet valido.",
zip: "Por favor inserte un codigo postal valido.",
confirm: "La contraseña de controlo no es igual a la contraseña original."
}
And make new default validation:
zip: {type: “zip”, re: /^\d{5}(-\d{4})?$/i}
Hi,Lennart Pilon
I want to validate when the input box has values.
how can I do .thinks.
@davcaffa: thnx, I added your translation and validation to the code.
@Rory Ye: if you want to match a non-empty string you can use the ‘required’ validation.
Sorry for my fuzzy expression,
I just want to validate the “real” when user input some text in the box. and this field is not required.
but when I add “real” validator in this filed and input nothing,Then the errors show “Please enter a valid number.”
clear? thinks.
Clear: you want to check for real or empty. Don’t know how to do that using regular expressions though, sorry. If you find a solution, can you let me know? Thnx!
portuguese validation:
pt: { required: “Este campo é de preenchimento obrigatório.”,
alpha: “Este campo só aceita caracteres alfanuméricos.”,
alphanum: “Este campo só aceita caracteres alfanuméricos.”,
integer: “Digite um número inteiro válido.”,
real: “Digite números válidos.”,
date: “Digite uma data válida (mm/dd/yyyy).”,
dateISO8601:”Digite uma data válida (yyyy-mm-dd).”,
dateEU: “Digite uma data válida (mm-dd-yyyy).”,
email: “Preencha o campo com um e-mail válido.”,
phone: “Digite um número de telefone válido.”,
url: “Digite um URL válido.”,
confirm: “A Password de confirmação não é igual à Password original.”
},
cheers
Hi,Lennart I just change this
_validate: function(field, options) {
switch(options.type) {
case “confirm”:
if($(options.idField).get(‘value’) == field.get(‘value’)) this._msgRemove(field, options);
else this._msgInject(field, options);
break;
case “required”:
if(options.re.test(field.get(‘value’))) this._msgRemove(field, options);
else this._msgInject(field, options);
break;
default:
if(field.get(‘value’)==”") break;
if(options.re.test(field.get(‘value’))) this._msgRemove(field, options);
else this._msgInject(field, options);
}
},
add this line
if(field.get(‘value’)==”") break;
and worked for me.
Good to see you found a solution to your problem!
I man
I made some a modification to Your good class
The modification use Asset for charge dynamic inclusion for the language .
Here is the modified class:
[code]var fValidator = new Class({
Implements: [Events, Options],
options: {
msgContainerTag: "div",
msgClass: "fValidator-msg",
styleNeutral: {"background-color": "#fff", "border-color": "#369"},
styleInvalid: {"background-color": "#fcc", "border-color": "#c00"},
styleValid: {"background-color": "#cfc", "border-color": "#0c0"},
language: "en",
// Absolute path to languages
languagesPath: './fValidator-lang/',
required: {type: "required", re: /[^.*]/},
alpha: {type: "alpha", re: /^[a-z ._-]+$/i},
alphanum: {type: "alphanum", re: /^[a-z0-9 ._-]+$/i},
integer: {type: "integer", re: /^[-+]?\d+$/},
real: {type: "real", re: /^[-+]?\d*\.?\d+$/},
date: {type: "date", re: /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/},
dateISO8601: {type: "dateISO8601", re: /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/},
dateEu: {type: "dateEU", re: /^(((([1-9])|([0-2][0-9])|(3[01]))[-]((0[13578])|([13578])|(1[02])))|((([1-9])|([0-2][0-9])|(30))[-]((0[469])|([469])|(11)))|((([1-9])|([0-2][0-9])))[-](2|02))[-]\d{4}$|^\d{4}$/},
email: {type: "email", re: /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i},
phone: {type: "phone", re: /^[\d\s ().-]+$/},
url: {type: "url", re: /^(http|https|ftp)\:\/\/[a-z0-9\-\.]+\.[a-z]{2,3}(:[a-z0-9]*)?\/?([a-z0-9\-\._\?\,\'\/\\\+&%\$#\=~])*$/i},
zip: {type: "zip", re: /^\d{5}(-\d{4})?$/i},
confirm: {type: "confirm"},
onValid: Class.empty,
onInvalid: Class.empty
},
initialize: function(form, options) {
this.setOptions(options);
// charge js language
var testar = new Asset.javascript(this.options.languagesPath + this.options.language + '.js', {id: 'fValidatorLang'});
// set language
//this.languageConfig = i18n;
this.form = $(form);
this.fields = this.form.getElements("*[class^=fValidate]");
this.validations = [];
this.fields.each(function(element) {
if(!this._isChildType(element)) element.setStyles(this.options.styleNeutral);
element.cbErr = 0;
var classes = element.getProperty("class").split(' ');
classes.each(function(klass) {
if(klass.match(/^fValidate(\[.+\])$/)) {
var aFilters = eval(klass.match(/^fValidate(\[.+\])$/)[1]);
for(var i = 0; i < aFilters.length; i++) {
if(this.options[aFilters[i]]) this.register(element, this.options[aFilters[i]]);
if(aFilters[i].charAt(0) == '=') this.register(element, $extend(this.options.confirm, {idField: aFilters[i].substr(1)}));
}
}
}.bind(this));
}.bind(this));
this.form.addEvents({
"submit": this._onSubmit.bind(this),
"reset": this._onReset.bind(this)
});
},
register: function(field, options) {
field = $(field);
this.validations.push([field, options]);
field.addEvent("blur", function() {
this._validate(field, options);
}.bind(this));
},
_isChildType: function(el) {
var elType = el.type.toLowerCase();
if((elType == "radio") || (elType == "checkbox")) return true;
return false;
},
_validate: function(field, options) {
switch(options.type) {
case "confirm":
if($(options.idField).get('value') == field.get('value')) this._msgRemove(field, options);
else this._msgInject(field, options);
break;
default:
if(options.re.test(field.get('value'))) this._msgRemove(field, options);
else this._msgInject(field, options);
}
},
_validateChild: function(child, options) {
var nlButtonGroup = this.form[child.getProperty("name")];
var cbCheckeds = 0;
var isValid = true;
for(var i = 0; i 0) isValid = false;
}.bind(this));
if(!isValid) event.stop();
return isValid;
},
_onReset: function() {
this.validations.each(function(array) {
if(!this._isChildType(array[0])) array[0].setStyles(this.options.styleNeutral);
array[0].cbErr = 0;
this._msgRemove(array[0], array[1], true);
}.bind(this));
}
});[/code]
And the included languages files structure is:
[code]var i18n = {
required: "This field is required.",
alpha: "This field accepts alphabetic characters only.",
alphanum: "This field accepts alphanumeric characters only.",
integer: "Please enter a valid integer.",
real: "Please enter a valid number.",
date: "Please enter a valid date (mm/dd/yyyy).",
dateISO8601:"Please enter a valid date (yyyy-mm-dd).",
dateEU: "Please enter a valid date (mm-dd-yyyy).",
email: "Please enter a valid email.",
phone: "Please enter a valid phone.",
url: "Please enter a valid url.",
zip: "Please enter a valid zip code.",
confirm: "Confirm Password does not match original Password."
};[/code]
Here [url]http://davidecaffaratti.com/upload/fValidator.zip[/url] can download the complete script (added compressed version of the class) and, sure, if You want can put all file in on Your site
Hi, great work
I just wanted the same as @Rory Ye, but I changed the regular expressions to have a * instead a +
But… i may part _validate into “required” and “default” because a required date input gets validated twice when empty, and i think i’ll give only one message to the user…