es.hideout-lastation.com
Paraíso Para Los Diseñadores Y Desarrolladores


Introducción a la validación de restricciones HTML5

Los sitios web interactivos y las aplicaciones no se pueden imaginar sin formularios que nos permitan conectarnos con nuestros usuarios y obtener los datos que necesitamos para asegurar transacciones fluidas con ellos. Necesitamos una entrada de usuario válida, sin embargo, necesitamos adquirirla de una manera que no frustre demasiado a nuestros usuarios.

Si bien podemos mejorar la usabilidad de nuestros formularios con patrones de diseño de UX elegidos con inteligencia, HTML5 también tiene un mecanismo nativo para la validación de restricciones que nos permite detectar errores de entrada directamente en el front-end .

En esta publicación, nos enfocaremos en la validación de restricciones suministradas por el navegador, y veremos cómo los desarrolladores frontend pueden asegurar la entrada de usuarios válidos usando HTML5 .

Por qué necesitamos la validación de entrada de entrada

La validación de entrada tiene dos objetivos principales. El contenido que recibimos debe ser:

1. Útil

Necesitamos datos utilizables con los que podamos trabajar . Necesitamos que las personas ingresen datos realistas en el formato correcto . Por ejemplo, nadie que esté vivo hoy nació hace 200 años. Obtener datos como este puede parecer divertido al principio, pero a largo plazo es molesto y rellena nuestra base de datos con datos inútiles.

2. Seguro

Cuando se hace referencia a la seguridad, esto significa que debemos evitar la inyección de contenido malicioso, ya sea deliberado o por accidente.

La utilidad (obtener datos razonables) se puede lograr solo en el lado del cliente, el equipo de back-end no puede ayudar demasiado con esto. Para lograr la seguridad, los desarrolladores de front-end y back-end deben trabajar en conjunto .

Si los desarrolladores de frontend validan correctamente la entrada del lado del cliente, el equipo de back-end tendrá que lidiar con muchas menos vulnerabilidades . La piratería (un sitio) a menudo implica el envío de datos adicionales, o datos en el formato incorrecto . Los desarrolladores pueden luchar contra agujeros de seguridad como estos, luchar con éxito desde el front-end.

Por ejemplo, esta guía de seguridad de PHP recomienda verificar todo lo que podamos en el lado del cliente. Ellos enfatizan la importancia de la validación de entrada frontend dando muchos ejemplos, tales como:

"La validación de entrada funciona mejor con valores extremadamente restringidos, por ejemplo, cuando algo debe ser un entero, una cadena alfanumérica o una URL HTTP".

En la validación de entrada frontend, nuestro trabajo es imponer restricciones razonables a la entrada del usuario. La característica de validación de restricciones de HTML5 nos proporciona los medios para hacerlo.

Validación de restricciones HTML5

Antes de HTML5, los desarrolladores de frontend se limitaban a validar la entrada del usuario con JavaScript, que era un proceso tedioso y propenso a errores. Para mejorar la validación de formulario del lado del cliente, HTML5 ha introducido un algoritmo de validación de restricciones que se ejecuta en los navegadores modernos y verifica la validez de la entrada enviada .

Para realizar la evaluación, el algoritmo utiliza los atributos relacionados con la validación de los elementos de entrada, como , </code>, and <code><select></code>. If you want to know how constraint validation happens step by step in the browser check out this WhatWG doc.</p> <p>Thanks to HTML5's constraint validation feature, we can execute all <strong>standard input validation tasks</strong> on the client side <strong>without JavaScript, solely with HTML5</strong>.</p> <p>To perform more complex validation-related tasks, HTML5 provides us with a <strong>Constraint Validation JavaScript API</strong> we can use to set up our custom validation scripts.</p> <h4>Validate with Semantic Input Types</h4> <p>HTML5 has introduced <strong>semantic input types</strong> that — apart from indicating the meaning of the element for user agents — can also be used to <strong>validate user input</strong> by limiting users to a certain input format.</p> <p>Besides the input types that have already existed before HTML5 (<code>text</code>, <code>password</code>, <code>submit</code>, <code>reset</code>, <code>radio</code>, <code>checkbox</code>, <code>button</code>, <code>hidden</code>), we can also use the following <strong>semantic HTML5 input types</strong>: <code>email</code>, <code>tel</code>, <code>url</code>, <code>number</code>, <code>time</code>, <code>date</code>, <code>datetime</code>, <code>datetime-local</code>, <code>month</code>, <code>week</code>, <code>range</code>, <code>search</code>, <code>color</code>.</p> <p>We can safely use HTML5 input types with older browsers, as they will behave as an <code><input type=text></code> field in browsers that don't support them.</p> <p>Let's see what happens when the user enters the wrong input type. Say we have created an email input field with the following code:</p> <pre name=code> <form name=form action=# method=post> <label for=youremail>Your Email:</label> <input type=email name=email id=youremail> <input type=submit value=Submit> </form> </pre> <p>When the user types a string that doesn't use an email format, the constraint validation algorithm <strong>doesn't submit the form</strong>, and <strong>returns an error message</strong>:</p> <img src=//hideout-lastation.com/img/tech-design-tips/615/intro-into-html5-constraint-validation.jpg>The same rule applies to other input types as well, for example for <code>type="url"</code> users can only submit an input that follows the URL format (starts with a protocol, such as <code>http://</code> or <code>ftp://</code>).</p> <p>Some input types use a design that <strong>doesn't even allow users to enter a wrong input format</strong>, for example <code>color</code> and <code>range</code>.</p> <pre name=code> <form name=form action=# method=post> <label for=bgcol>Background Color:</label> <input type=color name=color id=bgcol> <input type=submit value=Submit> </form> </pre> <p>If we use the <code>color</code> input type the user is constrained to either choosing a color from the color picker or staying with the default black. The input field is <strong>constrained by design</strong>, therefore it doesn't leave much chance for user error.</p> <img src=//hideout-lastation.com/img/tech-design-tips/615/intro-into-html5-constraint-validation-2.jpg>When it's appropriate, it's worth considering using the <code><select></code> HTML tag which works similarly to these constrained-by-design input types; it lets users choose from a dropdown list.</p> <pre name=code> <form name=form action=# method=post> <label for=favfruit>Your Favourite Fruit:</label> <select name=fruit id=favfruit> <option value=apple>Apple</option> <option value=pear>Pear</option> <option value=orange>Orange</option> <option value=raspberry>Raspberry</option> </select> <input type=submit value=Submit> </form> </pre> <img src=//hideout-lastation.com/img/tech-design-tips/615/intro-into-html5-constraint-validation-3.jpg>Use HTML5's Validation Attributes</h4> <p>Using semantic input types sets certain constraints on what users are allowed to submit, but in many cases we want to go a little bit further. This is when the <strong>validation-related attributes</strong> of the <code><input></code> tag can help us out.</p> <p>Validation-related attributes belong to certain input types (they can't be used on <em>all</em> types) on which they impose further constraints.</p> <h5>1. <code>required</code> for getting a valid input by all means</h5> <p>The <code>required</code> attribute is the most well-known HTML validation attribute. It's a <strong>boolean attribute</strong> which means it <strong>doesn't take any value</strong>, we just simply have to place it inside the <code><input></code> tag if we want to use it:</p> <pre name=code> <input type=email name=email id=youremail required> </pre> <p>If the user forgets to enter a value into a required input field, the browser <strong>returns an error message</strong> that warns them to fill in the field, and they <strong>can't submit the form</strong> until they have provided a valid input. That's why it's important to always <strong>mark visually</strong> required fields to users.</p> <p>The <code>required</code> attribute can be <strong>used together with the following input types</strong>: <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code>, <code>password</code>, <code>date</code>, <code>datetime</code>, <code>datetime-local</code>, <code>month</code>, <code>week</code>, <code>time</code>, <code>number</code>, <code>checkbox</code>, <code>radio</code>, <code>file</code>, plus with the <code><textarea></code>and <code><select></code> HTML tags.</p> <h5>2. <code>min</code>, <code>max</code> and <code>step</code> for number validation</h5> <p>The <code>min</code>, <code>max</code> and <code>step</code> attributes enable us to <strong>put constraints on number input fields</strong>. They can be used together with the <code>range</code>, <code>number</code>, <code>date</code>, <code>month</code>, <code>week</code>, <code>datetime</code>, <code>datetime-local</code>, and <code>time</code> input types.</p> <p>The <code>min</code> and <code>max</code> attributes provide a great way to easily <strong>exclude unreasonable data</strong>. For instance the example below forces users to submit an age between 18 and 120.</p> <pre name=code> <form name=form action=# method=post> <label for=yourage>Your Age:</label> <input type=number name=age id=yourage min=18 max=120> <input type=submit value=Submit> </form> </pre> <p>When the constraint validation algorithm bumps into a user input smaller than the <code>min</code>, or larger than the <code>max</code> value, it prevents it from reaching the backend, and returns an error message.</p> <img src=//hideout-lastation.com/img/tech-design-tips/615/intro-into-html5-constraint-validation-4.jpg>The <code>step</code> attribute <strong>specifies a numeric interval</strong> between the legal values of a numeric input field. For instance, if we want users to choose only from leap years we can add the <code>step="4"</code> attribute to the field. In the example below I used the <code>number</code> input type, as there's no <code>type="year"</code> in HTML5.</p> <pre name=code> <form name=form action=# method=post> <label for=yourleapyear>Your Favourite Leap Year:</label> <input type=number name=leapyear id=yourleapyear min=1972 max=2016 step=4> <input type=submit value=Submit> </form> </pre> <p>With the pre-set constraints, users can only choose from leap years between 1972 and 2016 if they use the little up-arrow that comes with the <code>number</code> input type. They can also type a value manually into the input field, but in case it doesn't meet the constraints, the browser will return an error message.</p> <img src=//hideout-lastation.com/img/tech-design-tips/615/intro-into-html5-constraint-validation.gif>3. <code>maxlength</code> for text length validation</h5> <p>The <code>maxlength</code> attribute makes it possible to <strong>set a maximum character length</strong> for textual input fields. It can be used together with the <code>text</code>, <code>search</code>, <code>url</code>, <code>tel</code>, <code>email</code> and <code>password</code> input types, and with the <code><textarea></code> HTML tag.</p> <p>The <code>maxlength</code> attribute can be an excellent solution for phone number fields that cannot have more than a certain number of characters, or for contact forms where we don't want users to write more than a certain length.</p> <p>The code snippet below shows an example for the latter, it constraints user messages to 500 characters. </p> <pre name=code> <form name=form action=# method=post> <label for=yourmsg>Message (max 500 characters):</label> <textarea name=msg id=yourmsg cols=25 rows=4 maxlength=500>

El atributo maxlength no devuelve un mensaje de error, pero el navegador simplemente no permite a los usuarios escribir más que el número de carácter especificado. Es por eso que es crucial informar a los usuarios sobre la restricción, de lo contrario no entenderán por qué no pueden seguir escribiendo.

4. pattern para la validación de Regex

El atributo de pattern nos permite usar expresiones regulares en nuestro proceso de validación de entrada. Una expresión regular es un conjunto predefinido de caracteres que forman un determinado patrón. Podemos usarlo para buscar cadenas que sigan el patrón o para aplicar un determinado formato definido por el patrón.

Con el atributo de pattern podemos hacer lo segundo: restringir a los usuarios a enviar su entrada en un formato que coincida con la expresión regular dada .

El atributo de pattern tiene muchos casos de uso, pero puede ser especialmente útil cuando queremos validar un campo de contraseña .

El siguiente ejemplo requiere que los usuarios ingresen una contraseña que tiene un mínimo de 8 caracteres y contiene al menos una letra y un número (fuente de la expresión regular que utilicé).

Algunas cosas más

En este artículo, echamos un vistazo a cómo utilizar la validación de formularios proporcionada por el navegador proporcionada por el algoritmo de validación de restricciones nativo de HTML5. Para crear nuestros scripts de validación personalizados, debemos usar la API de validación de restricciones que puede ser el siguiente paso para perfeccionar las habilidades de validación de formularios.

Los formularios HTML5 son accesibles mediante tecnologías de asistencia, por lo que no necesariamente tenemos que usar el atributo ARIA aria-required para marcar los campos de entrada necesarios para los lectores de pantalla. Sin embargo, puede ser útil agregar compatibilidad de accesibilidad para navegadores antiguos. También es posible inhabilitar la validación de restricciones agregando el novalidate booleano novalidate al

elemento.

20 hermosas casas en el lago que te encantaría tener [PICS]

20 hermosas casas en el lago que te encantaría tener [PICS]

Una casa refleja muchas cosas sobre ti . Las casas flotantes son excelentes ejemplos de casas que no solo son capaces de combinar forma y funcionalidad, sino que en la mayoría de los casos, también consideran el entorno y cómo usarlo por completo. Por supuesto, también hay algo relajante en estar rodeado de agua. Le

(Consejos de tecnología y diseño)

Lecciones de autoorganización que puede aprender de estudiantes alemanes

Lecciones de autoorganización que puede aprender de estudiantes alemanes

He vivido en Alemania durante cinco años y he interactuado con personas de casi todos los ámbitos de la vida. Cuando vine aquí para un programa de maestría, mi exposición más extensa ha sido con estudiantes alemanes.Este interesante grupo de personas que se suenan ruidosamente en la clase y muestran su gratitud a la maestra tocando el escritorio cuando finaliza la clase, también poseen fuertes habilidades de autoorganización integradas en sus personalidades .Viniend

(Consejos de tecnología y diseño)