📜 ⬆️ ⬇️

Validating JavaScript with Valid8

Often it is necessary to “saturate” interfaces with the help of JavaScript. I mainly work through jQuery, I like everything, but one problem is validation. Constantly it is necessary to invent a "bicycle", search for snippets of code on the network; and after all it would be desirable to write couple of lines without deepening in a detail. Joy was not long in coming: I found the Valid8 library (pronounced validate), and finally solved the problem of writing validation code.

How to use


Using the library turned out to be very simple, which cannot be said about gluing jQuery “scraps” from the Internet. To connect the library, you need to go here and click on the coveted Download . An archive is downloaded in which the jquery.valid8.js file is of particular interest, we copy it into the folder with the js files of our project and include the library in html:
<script src="/js/jquery-1.6.3.js" type="text/javascript" charset="utf-8"></script> <script src="/js/jquery.valid8.js" type="text/javascript" charset="utf-8"></script> 

Suppose we have a form:
 <form><ul> <li><input type="text" id="inputSome" /></li> </ul></form> 

We add a validation (by default, only a check for mandatory filling), passing a string with an error message as a parameter. We work in jQuery style:
 $('#inputSome').valid8("  !"); 

After the field gets the focus and you exit it without filling it out, the enclosing tag (in our case li ) will get the error style class.
To visualize errors, add CSS to the head of our document:
 <style> .error input { background:pink; } </style> 

Validation is ready. Everything.


Opportunities more interesting


The functionality of Valid8 is not limited to the fill check. For serious work, you can connect regular expressions:
 $('#inputSome').valid8({ 'regularExpressions': [ { expression: /^.+$/, errormessage: '  !'}, { expression: /^[habr]+$/|>, errormessage: '     h, a, b, r'} ] }); 

Now, only characters matching both regular expressions can be entered into the field. The first prohibits leaving the field empty, and the second adds a restriction on entering 4 characters: you can enter habr , babr , habrahabr , or something derivative corresponding to the expression.
')

Well, Ajax, of course


You can use the server for validation:
 $('#inputSome').valid8({ 'ajaxRequests': [ { url: '/ajax/validation/' } ] }); 

Now the library will communicate with the server to verify the entered value (for example, to warn about a registered login). The value in the field is transmitted to the server via POST in the value parameter. The server should return a response in JSON format:
 {"valid": true, "message": ",    !"} 

You can combine validation on regular expressions and server. There are other possibilities: the definition of the event for which validation occurs, the check interval, the validation function js.

Sources

Valid8 library
JQuery library

Source: https://habr.com/ru/post/128321/


All Articles