it.hideout-lastation.com
Paradiso Per Designer E Sviluppatori


Introduzione alla convalida del vincolo HTML5

I siti Web e le applicazioni interattivi non possono essere immaginati senza moduli che ci consentano di connettersi con i nostri utenti e di ottenere i dati di cui abbiamo bisogno per garantire transazioni senza intoppi con loro. Abbiamo bisogno di input validi per l'utente, tuttavia dobbiamo acquisirlo in un modo che non sia di disturbo per gli utenti.

Anche se possiamo migliorare l'usabilità dei nostri moduli con modelli di progettazione UX scelti in modo intelligente, HTML5 ha anche un meccanismo nativo per la convalida dei vincoli che ci consente di individuare gli errori di input direttamente nel front-end .

In questo post, ci concentreremo sulla convalida dei vincoli fornita dal browser e esamineremo in che modo gli sviluppatori frontend possono proteggere l'input dell'utente valido utilizzando HTML5 .

Perché abbiamo bisogno della convalida dell'input dei front-end

La convalida dell'input ha due obiettivi principali. Il contenuto che otteniamo deve essere:

1. Utile

Abbiamo bisogno di dati utilizzabili con cui possiamo lavorare . Dobbiamo far sì che le persone inseriscano dati realistici nel formato giusto . Ad esempio, nessuno che è vivo oggi è nato 200 anni fa. Ottenere dati come questo può sembrare strano all'inizio, ma a lungo termine è fastidioso e popola il nostro database con dati inutili.

2. Sicuro

Quando ci si riferisce alla sicurezza, ciò significa che dobbiamo impedire l'immissione di contenuti dannosi, intenzionali o accidentali.

L'utilità (ottenendo dati ragionevoli) può essere raggiunta solo dal lato del cliente, il team di back-end non può aiutare troppo con questo. Per raggiungere la sicurezza, gli sviluppatori di front e back-end devono collaborare .

Se gli sviluppatori di frontend validano correttamente l'input sul lato client, il team di back - end dovrà gestire meno vulnerabilità . L'hacking (un sito) comporta spesso l' invio di dati aggiuntivi o dati nel formato sbagliato . Gli sviluppatori possono combattere buche di sicurezza come queste, combattere con successo dal front-end.

Ad esempio, questa guida alla sicurezza di PHP consiglia di controllare tutto ciò che possiamo dal lato client. Sottolineano l'importanza della convalida dell'input di frontend fornendo molti esempi, come ad esempio:

"La validazione degli input funziona meglio con valori estremamente limitati, ad esempio quando qualcosa deve essere un numero intero o una stringa alfanumerica o un URL HTTP."

Nella convalida dell'input del frontend, il nostro compito è imporre limiti ragionevoli all'input dell'utente. La funzione di convalida dei vincoli di HTML5 ci fornisce i mezzi per farlo.

Convalida vincoli HTML5

Prima di HTML5, gli sviluppatori di frontend erano limitati a convalidare l'input dell'utente con JavaScript, che era un processo noioso e soggetto a errori. Per migliorare la convalida dei moduli lato client, HTML5 ha introdotto un algoritmo di convalida dei vincoli che viene eseguito nei browser moderni e controlla la validità dell'input presentato .

Per effettuare la valutazione, l'algoritmo utilizza gli attributi relativi alla validazione degli elementi di input, come ad esempio , </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>

L'attributo maxlength non restituisce un messaggio di errore, ma il browser semplicemente non consente agli utenti di digitare più del numero di carattere specificato. Ecco perché è fondamentale informare gli utenti sul vincolo, altrimenti non capiranno perché non possono continuare con la digitazione.

4. pattern per la convalida del Regex

L'attributo pattern ci consente di utilizzare le espressioni regolari nel nostro processo di convalida dell'input. Un'espressione regolare è un insieme predefinito di caratteri che formano un determinato modello. Possiamo usarlo sia per cercare stringhe che seguono il modello, sia per far rispettare un determinato formato definito dal pattern.

Con l'attributo pattern possiamo fare il secondo - costringere gli utenti a inviare i loro input in un formato che corrisponda all'espressione regolare data .

L'attributo pattern ha molti casi d'uso, ma può essere particolarmente utile quando vogliamo convalidare un campo password .

L'esempio seguente richiede agli utenti di inserire una password di almeno 8 caratteri e che contenga almeno una lettera e un numero (fonte della regex che ho usato).

Ancora un paio di cose

In questo articolo, abbiamo esaminato come utilizzare la convalida del modulo fornita dal browser fornita dall'algoritmo di convalida nativo di HTML5. Per creare i nostri script di convalida personalizzati, è necessario utilizzare l'API Convalida convalida che può essere il prossimo passo per perfezionare le abilità di convalida dei moduli.

I moduli HTML5 sono accessibili tramite tecnologie assistive, quindi non è necessario utilizzare aria-required attributo ARIA aria-required per contrassegnare i campi di input richiesti per gli screen reader. Tuttavia può essere ancora utile aggiungere il supporto dell'accessibilità per i browser più vecchi. È anche possibile disattivare la convalida dei vincoli aggiungendo l' novalidate booleano novalidate al

elemento.

Inspirational Workspace: 60 fantastici setup

Inspirational Workspace: 60 fantastici setup

Passiamo la maggior parte della giornata davanti ai nostri computer. È qui che vengono eseguite tutte le attività, vengono prese in considerazione le e-mail e si creano relazioni sociali. La verità è che il computer è diventato un elemento fondamentale per quasi ogni aspetto dello stile di vita moderno, e ora le persone stanno persino adottando più dispositivi per migliorare le proprie competenze lavorative.Dopo

(Consigli tecnici e di design)

10 framework PHP per sviluppatori - Il meglio di

10 framework PHP per sviluppatori - Il meglio di

PHP, noto come il linguaggio di scripting lato server più famoso al mondo, si è evoluto molto da quando i primi frammenti di codice inline sono stati visualizzati in file HTML statici.Oggigiorno gli sviluppatori hanno bisogno di costruire siti Web e applicazioni web complessi e, al di sopra di un certo livello di complessità , può richiedere troppo tempo e problemi per iniziare sempre da zero, da qui la necessità di un modo di sviluppo più strutturato e naturale. I fr

(Consigli tecnici e di design)