jueves, 11 de mayo de 2017

Easy validation of forms with javascript

DjValidator is a jQuery plugin for validating HTML forms in a simple, fast and flexible way, it is compatible with bootstrap and any other web design framework.

Only add the jquery library, DjValidator and call a Validation method, the validation parameters are defined by placing A single attribute in the fields (data-dj-validator) In addition to the attribute required.


How to download:

With NPM : npm install djvalidator                           NPM page
With Bower: bower install djvalidator
Github: https://github.com/esneyderg357/DjValidator



Example:

Include the files of the jQuery library and the DjValidator plugin in your HTML document:

 <script type="text/javascript" src="/ruta/a/jquery.js"></script>
 <script type="text/javascript" src="/ruta/a/DjValidator.js"></script>


To use the DjValidator plugin call the functiondjValidator() selecting a form:

 $('#form').djValidator(); //To add the validator to the event submit


If you use ajax or just want to validate (true or false) use:

 $('#form').djValidator('validate'); //returns true o false


Add the validation parameters you require in each form field:

<form id="form" class="form-horizontal">
<fieldset>
<legend>Campos de texto</legend>
<div class="form-group">
  <label class="col-md-4 control-label" for="textarea">Texto (text)</label>
  <div class="col-md-8">                
    <textarea class="form-control" name="textarea" data-dj-validator="text,3,12" required></textarea>
  </div>
</div>
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Texto alfabético (atext)</label>
  <div class="col-md-8">
  <input name="textinput" type="text" class="form-control input-md" data-dj-validator="atext,3,12" required>
  </div>
</div>
</fieldset>
<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton"></label>
  <div class="col-md-8">
    <button type="submit" id="validate" name="singlebutton" class="btn btn-primary">Enviar</button>
  </div>
</div>
</form>



Reference of all possible validations HERE
More information in other entries.

Validación fácil de formularios con javascript

DjValidator es un plugin de jquery para validación de formularios HTML de forma simple, rápida y flexible, es compatible con bootstrap y cualquier otro framework de diseño web.

Solo agregue la libreria de jquery, la libreria de  DjValidator y llame a un método de validación, los parámetros de validación se definen colocando un único atributo en los campos (data-dj-validator) además del atributo required.


Como descargar:

Con NPM : npm install djvalidator                           página NPM
Con Bower: bower install djvalidator
Github: https://github.com/esneyderg357/DjValidator


Ejemplo:

Incluya los archivos de la librería de jQuery y el plugin DjValidator en su documento HTML:

 <script type="text/javascript" src="/ruta/a/jquery.js"></script>
 <script type="text/javascript" src="/ruta/a/DjValidator.js"></script>

Para usar el validador en español incluya otro archivo adicional:

<script type="text/javascript" src="/ruta/a/DjValidator-es.js"></script>

Para usar el plugin DjValidator llame a la  función  djValidator() seleccionando un formulario:

 $('#form').djValidator(); //para agregar el validador al evento submit


Si utiliza ajax o quiere solo realizar validación (true o false) use:

 $('#form').djValidator('validate'); //método que devuelve true o false


Agregue los parámetros de validación que requiera en cada campo del formulario:

<form id="form" class="form-horizontal">
<fieldset>
<legend>Campos de texto</legend>
<div class="form-group">
  <label class="col-md-4 control-label" for="textarea">Texto (text)</label>
  <div class="col-md-8">                
    <textarea class="form-control" name="textarea" data-dj-validator="text,3,12" required></textarea>
  </div>
</div>
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Texto alfabético (atext)</label>
  <div class="col-md-8">
  <input name="textinput" type="text" class="form-control input-md" data-dj-validator="atext,3,12" required>
  </div>
</div>
</fieldset>
<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton"></label>
  <div class="col-md-8">
    <button type="submit" id="validate" name="singlebutton" class="btn btn-primary">Enviar</button>
  </div>
</div>
</form>



Referencia de todas las validaciones posibles AQUI
Más información en las demás entradas.

miércoles, 12 de abril de 2017

DjValidator - español

Descripción

DjValidator es un plugin de jquery para validación de formularios en el front-end de forma simple, rápida y flexible, es compatible con bootstrap y cualquier otro framework de diseño web.

Características:
  • ·        Solo requiere Jquery, 1.5.1 o superior, no depende de ningún framework de UI.
  • ·         Las reglas de validación se colocan usando un único atributo (data-dj-validator), además reconoce el atributo “required” y valida el campo como obligatorio.
  • ·         El plugin requiere un máximo de 2 parámetros.
  • ·         Juego de reglas de validación multifuncionales compacto, escritura rápida.
  • ·         Diferentes formas de aplicar la validación.
  • ·         Capacidad de crear validadores propios usando 3 alternativas.
  • ·         Capacidad de modificar las reglas de validación de forma dinámica.
  • ·         Capacidad de modificar o traducir los mensajes de validación.
  • ·         Capacidad de cambiar el estilo de los mensajes de validación.
  • ·         Se pueden modificar el estilo y mensajes de forma global, evitando especificar en cada uso del validador.


Todos los ejemplos y descripciones utilizan bootstrap, aunque la libreria no lo requiere.

Descarga

Descargue DjValidator desde npm: npm install djvalidator

Descargue DjValidator desde bower: bower install djvalidator

En GitHub: https://github.com/esneyderg357/DjValidator
npm : https://www.npmjs.com/package/djvalidator

Instalación

para usar DjValidator, incluya los archivos de la librería de jQuery y el plugin DjValidator en su documento HTML:

<script type="text/javascript" src="/ruta/a/jquery.js"></script>
<script type="text/javascript" src="/ruta/a/DjValidator.js"></script>

Utilice jquery 1.5 o superior.


Como usar el plugin:

Puede encontrar todos los ejemplos de uso en la descarga.

1. Agregue los scripts de jquery and djValidator:

<script type="text/javascript" src="../lib/jquery/jquery.js"></script>

    <script type="text/javascript" src="../dist/DjValidator.js"></script>

2. Coloque las reglas de validación:

Agregue el atributo “novalidate”, para deshabilitar la validación del navegador.

Agregue la regla de validación en los campos necesarios (data-dj-validator), use el atributo 'required' para campos obligatorios:

<input name="input1" type="text" data-dj-validator="atext,3,12" required>

Reglas disponibles: http://djvalidator.blogspot.com/2017/04/validators-reference.html 


3. Use el plugin con alguna de estas formas:

La validación se ejecuta en el evento submit del formulario, evitando el envío de ser no válido:

$('#form').djValidator(); 

La validación se ejecuta en el evento submit del formulario, evita el envío y ejecuta la función parámetro en caso de ser válido:

$('#form').djValidator('callback',function($form){

alert("Callback executed when the form is valid.");

});

La validación se ejecuta en el momento de ejecutar el plugin, devuelve true o false según el resultado:

var resp=$('#form').djValidator('validate');

alert("only validate form: "+resp);

La validación se ejecuta solo sobre un campo en el momento de ejecutar el plugin, devuelve true o false según el resultado:

var resp=$('#input1').djValidator('field')

alert("only validate a field: "+resp);

Borra todos los mensajes de validación colocados por el validador (limpieza):

$('#form').djValidator('clean');

Referencia completa del API: http://djvalidator.blogspot.com/2017/04/api-reference.html 

Personalización:

Personalizar mensajes de validación:

                 <input name="user" required data-dj-validator-msg="Please fill the user!">

Cambiar todos los mensajes de validación (vea en la traducción al español de la descarga el ejemplo completo):

$.setDjValidatorLabels({

required:'Campo requerido.',

word_min:'Por lo menos $1 caracteres sin espacios.',

word_between:'Entre $1 y $2 caracteres sin espacios.',

…………………………… });

Cambiar el estilo de forma global:

$.setDjValidatorStyle('display:none; text-align:center; color:white; background-color:red;');


Reglas de validación personalizadas

Se puede realizar de 3 formas:

1. Agregando una nueva regla de validación de forma global:

       <input name="textinput" type="text" data-dj-validator="regexp,^[aeiou]+$,i" required>

2. Llamando a una función propia de validación:

        <input name="textinput" type="text" data-dj-validator="call,isUpperCase" required>

     function isUpperCase($field){

value=$field.val();

if(value==value.toUpperCase())return true;

return false;

     }

3. Using regular expressions:

        <input name="textinput" type="text" data-dj-validator="even,10" required>

$.addDjValidator('even','only even numbers.',function($field,args){
value=parseInt($field.val());
max=args[1];
if(value%2!=1||value>max)return false;
return true;
});

Copyright (c) 2018 DjValidator fue desarrollado por David Esneyder Jerez Garnica. 

Licencia GPLv3

Otros plugins:
cargador de datos Json en html: DJsonLoader

API - español

API

Uso del plugin:

$(form).djValidator([mode],[callback])

Se debe invocar sobre formularios o campos de formularios.

Parámetro
Tipo
Descripción
mode
String
Opcional, es el modo en el que se usará el validador, si no se coloca por defecto se adjunta al evento  submit de los formularios.
Otros valores posibles son:
·     ‘callback’ : Se adjunta al evento submit del formulario y llama la función pasada en el parámetro [callback] cuando todos los campos son válidos.
·     ‘validate’ : Válida un formulario como una función y devuelve true o false, se usa cuando se envía el formulario por javascript (solo se invoca sobre un formulario).
·     ‘field’ : se invoca sobre un campo de formulario para validarlo, devuelve true o false (solo se invoca sobre un campo).

‘clean’ (v1.1.0) : Borra todos los mensajes de validación colocados en los formularios.
callback
function
Opcional, solo se especifica cuando el parámetro [mode] es ‘callback’ , es la función que debe ejecutarse cuando el formulario ya es válido, esta función debe recibir el formulario como parámetro.

Ejemplos:

Por defecto al evento submit:        
          
                 $(‘form’). djValidator();

Al evento submit, ejecuta la función cuando es válido:

                $(‘form’).djValidator(‘callback’,function($form){
                  //código
                  $form.submit();
});

Como función:

                  $(‘#myform’). djValidator(‘validate’);

Como función, valida solo un campo:    

         $(‘#myInput’). djValidator(‘field’);

Borrar mensajes de validación: 
               
         $(‘#myform’). djValidator(‘clean’);


Agregar un nuevo validador dentro de DjValidator:

      $.addDjvalidator(key,msg,callback);


Parámetro
Tipo
Descripción
key
String
Nombre de la clave a utilizar.
msg
String
Mensaje de validación.
callback
function
Función que realiza la validación, recibe 2 parámetros:
[$field] : El campo a validar (objeto).
[args] : Los parámetros de validación (array de strings).
La función debe retornar true o false.


Ejemplo:

$.addDjValidator('even','only even numbers.',function($field,args){
                       value=parseInt($field.val());
                       max=args[1];
                       if(value%2!=1||value>max)return false;
                       return true;
      });




Cambiar el estilo CSS de los mensajes de validación:

$.setDjvalidatorStyle(style);


Parámetro
Tipo
Descripción
style
String
Contiene los estilos a aplicar en el atributo “style” de los mensajes, se debe agregar  display:none;para ver un efecto de FadeIn.

Ejemplo:

$.setDjValidatorStyle('display:none; text-align:center; color:white; background-color:red;');




Cambiar los mensajes de validación de DjValidator para personalizarlos o traducirlos:

$.setDjValidatorLabels(labels);


Parámetro
Tipo
Descripción
labels
Object
Contiene los nombres y los mensajes en formato json, los parámetros reemplazables están precedidos del signo $.
Vea la traducción al español como referencia de los nombres de los mensajes.

Ejemplo (vea en la traducción al español el ejemplo completo):
                $.setDjValidatorLabels({
                required:'Campo requerido.',
                word_min:'Por lo menos $1 caracteres sin espacios.',
                word_between:'Entre $1 y $2 caracteres sin espacios.',
        …………………………… });



Atributos disponibles


The following attributes are used by DjValidator in the form fields:

Utilidad
Atributo
Descripción
Ejemplo
Validador a utilizar
data-dj-validator
Añade la validación al campo con la clave especificada (vea la tabla de claves de validación).

data-dj-validator="text,3,12"
Relacionar campos
data-dj-validator-group
Especifica un grupo de campos relacionados por el mismo nombre del atributo.

data-dj-validator-group=”lenguajes”
Mensaje de validación
data-dj-validator-msg
Define un mensaje de validación personalizado para el campo.

data-dj-validator-msg=”¡El nombre no es válido!”
Campo requerido (obligatorio)
required
El atributo required de HTML5 hace que el campo sea obligatorio.

required
Mensaje en campos compuestos
(v1.1.0)

data-input-group
Coloca el mensaje como hijo del elemento padre del campo, usado para corregir la posición del mensaje en campos compuestos por varios elementos. El valor utilizado es irrelevante.
data-input-group="group"


Separadores reconocidos en una regla de validación


The following characters are special within the validation key (data-dj-validator attribute):


Utilidad
Caracter
Descripción
Ejemplo
Separar validadores
&
Separa varias claves de validación.
“atext,3,12&word,3,12”
Separar parámetros
,
Separa los parámetros de una clave de validación
“Text,3,50”
Separar valores de un parámetro de validación de tipo array
|
Separa los valores de un parámetro de valores múltiples.
“efile,jpg|jpeg|png|bmp”
Omitir parámetro.
*
Omite la validación del parámetro siempre y cuando la clave lo permita (ver tabla de validadores).
“atext,5,*”
Reconocer comas
(v1.1.0)

       °Como la coma es un carácter especial para el validador, si se usan expresiones regulares con comas en el validador “regexp”, deben ser reemplazadas con este carácter."regexp,^[aeiou]{3°5}$,i"

API reference

API

Using the plugin:

$(form).djValidator([mode],[callback])

It should be invoked on forms or form fields.

Parameter
Type
Description
mode
String
Optional, is the mode in which the validator will be used, if not placed by default it is attached to the submit event of the forms.
Other possible values are:

• 'callback': It is attached to the submit event of the form and calls the function passed in the parameter [callback] when all fields are valid.

• 'validate': Valid a form as a function and returns true or false, used when sending the form by javascript (only invoked on a form).

• 'field': invoked on a form field to validate it, returns true or false (only invoked on a field).

• ‘clean’ (v1.1.0) : Borra todos los mensajes de validación colocados en los formularios.

callback
function
Optional, only specified when the [mode] parameter is 'callback', is the function that must be executed when the form is already valid, this function should receive the form as a parameter.


Examples:

By default to submit event:
       
                  $('form').djValidator();

To the submit event, execute the function when it is valid:

                 $('form').djValidator('callback', function($form){
               //code
               $form.submit();
         });

As function:

                   $ ('#myform').djValidator('validate');

As a function, validate only one field:

          $ ('#myInput').djValidator('field');

Erase validation messages: 
               
         $(‘#myform’). djValidator(‘clean’);

Add a new validator inside DjValidator:

      $.addDjvalidator(key,msg,callback);


Parameter
Type
Description
key
String
Name of the key to use.
msg
String
Validation message.
callback
function
Function that performs validation, receives 2 parameters:
[$field]: The field to validate (object).
[args]: The validation parameters (array of strings).
The function must return true or false.


Example:

$.addDjValidator('even','only even numbers.',function($field,args){
                       value=parseInt($field.val());
                       max=args[1];
                       if(value%2!=1||value>max)return false;
                       return true;
      });



Change the CSS style of the validation messages:

$.setDjvalidatorStyle(style);


Parameter
Type
Description
style
String
Contains the styles to apply in the "style" attribute of the messages, you must add "display: none;" to see a FadeIn effect.

Example:

$.setDjValidatorStyle('display:none; text-align:center; color:white; background-color:red;');




Change DjValidator validation messages to customize or translate:

$.setDjValidatorLabels(labels);


Parameter
Type
Description
labels
Object
Contains names and messages in json format, replaceable parameters are preceded by the $ sign.
See the Spanish translation as a reference of the names of the messages.

Example (See in the Spanish translation the complete example):
                $.setDjValidatorLabels({
                required:'Campo requerido.',
                word_min:'Por lo menos $1 caracteres sin espacios.',
                word_between:'Entre $1 y $2 caracteres sin espacios.',

        …………………………… });



Attributes to use


The following attributes are used by DjValidator in the form fields:


Utility
Attribute
Description
Example
Validator to use
data-dj-validator
Add validation to the field with the specified key (see validation key table).

data-dj-validator="text,3,12"
Relate fields
data-dj-validator-group
Specifies a group of related fields by the same attribute value.

data-dj-validator-group=”lenguajes”
Validation message
data-dj-validator-msg
Defines a custom validation message for the field.

data-dj-validator-msg=”Name is not valid!”
Field required
required
The required HTML5 attribute.

required
Message in compound fields
(v1.1.0)
data-input-groupPlace the message as a child of the parent element of the field, used to correct the position of the message in fields composed of several elements. The value used is irrelevant.data-input-group="group"



Separators recognized in a validation rule


The following characters are special within the validation key (data-dj-validator attribute):

Utility
Character
Description
Example
Separate validators
&
Separate multiple validation keys.
“atext,3,12&word,3,12”
Separate parameters
,
Separate the parameters of a validation key
“Text,3,50”
Separate values from an array-type validation parameter
|
Separates the values of a multi-valued parameter.
“efile,jpg|jpeg|png|bmp”
Omit parameter
*
Omits the parameter validation as long as the key allows it (see table of validators).

“atext,5,*”
Recognize commas (v1.1.0)
      °Since the comma is a special character for the validator, if regular expressions are used with commas in the "regexp" validator, they must be replaced with this character."regexp,^[aeiou]{3°5}$,i"