📜 ⬆️ ⬇️

Validation of forms in JavaScript Part 1

Introduction


Good afternoon, dear reader. In this article I would like to refer to the topic of checking the contents of forms on the client side. At the dawn of the development of languages ​​that work on the client, this task was primary. Over time, these languages ​​are overgrown with new features (DOM manipulation, style management, etc.), but the task of checking forms has not disappeared. However, with the advent of HTML5, it became possible to specify such a type of form field as email, and the browser itself will take over its verification. This feature is currently implemented in Opera, so it’s not particularly necessary to rely on it. Therefore, I would like to consider this question thoroughly. In most cases, the validation is performed like this: id is distributed to each field, and then with submit we pull them out, simultaneously checking the contents. And all this approach is good, except for the lack of consistency in it. Therefore, I want to offer you my solution to this problem.

So rushed!


As an example, a simple form is provided containing fields for name, mailbox and gender.
HTML file code:
<html> <head>     <style type="text/css">         input[type="text"] {                         border: 1px solid #D4E2F7;         }         input {             margin: 3px 0px 3px 15px;         }             </style>     <script type="text/javascript">           ....     </script> </head> <body>                  <form name="form" action="6.php" method="POST">         <input type="text" name="name" value="My name" /><br>         <input type="text" name="email" value="email@mail.com" /><br>         <input type="radio" name="sex" checked="checked" value="male" />male<br>         <input type="radio" name="sex" value="female" />female<br>         <input type="submit" value="Ok" />     </form> </body> </html> 

The rest of the code will be placed in the <script> tag.
First, create a function that will set all the required fields, pre-supplying them with properties. Field names are listed in the members array.

  function createField() {        var members = new Array('required', 'regexp');        for(var i = 0; i < arguments.length; i++) {            this[members[i]] = arguments[i];        }    }    // absolute regexp    createField.prototype.regexp = /^[A-z0-9-_+. ,@]{1,}$/ig;    createField.prototype.valid = false;    createField.prototype.required = true;    createField.prototype.nullify = function() {        this.valid = false;    }; 


Further, in the prototype, we indicate the default values ​​of the fields.
regexp is a regular field which the value of the corresponding field must satisfy.
valid is the result of checking the field value with a regexp regular expression.
required - an indicator of whether this field is required (can you leave the field blank).
nullify () is a method that returns a valid field to its original state.
')
 var single = new Array(); single['name'] = new createField(); single['email'] = new createField(true, /^[A-z0-9._-]+@[A-z0-9.-]+\.[Az]{2,4}$/); single['sex'] = new createField(true, /male$/ig); 

We create a prototype of our form. It will have 3 fields with the names name, email and sex, each of which can not be left empty. Moreover, the values ​​of the last 2 fields must satisfy the regular expression specified in the second parameter.
 var Singleton = {        fields : single,        regForm : false,        nullify_values : function() {            for(i in this.fields) {                this.fields[i].nullify();            }        },               ...        }; 

In this part of the code, we declare a Singleton object. The purpose of the fields field is clear. The regForm field is the object containing the form. Through it we will get access to the fields of the form and their values.
The nullify_values ​​() method returns the value of the valid field for “sub-objects” (since fields is an array of objects) to its original state.


And finally, the most interesting. The submit () method, which contains the main functionality.
 submit : function() { if(this.regForm) { // set property valid to false for every form field this.nullify_values(); var i = null; // walks through the form fields, pick and if required check their values for(i = 0; i < this.regForm.elements.length; i++) { // current field var oField = this.regForm.elements[i]; switch (oField.type) { case "button": case "submit": case "reset": break; case "checkbox": case "radio": if(!oField.checked) { break; } default : // javascript trim function analogue oField.value = oField.value.replace(/^\s*/, '').replace(/\s*$/, ''); if(!oField.value) { oField.value = ''; } // if this field is out of interest if(!this.fields[oField.name].required) { this.fields[oField.name].valid = true; this.regForm[i].style.border=""; } // if this field is required else { var match = this.fields[oField.name].regexp.test(oField.value); // ... and fits regular expression if(match) { this.fields[oField.name].valid = true; this.regForm[i].style.border=""; } this.fields[oField.name].regexp.test(oField.value); } } } // now all we need is to check if the whole form is valid // we perform it by comparing number of form fields and number of valid fields // they should be equal var validForm = 0; var fieldsLength = 0; for(i in this.fields) { fieldsLength++; if(this.fields[i].valid) { validForm++; } else { this.regForm[i].style.border="1px solid #FF0000"; break; } } if(validForm == fieldsLength) { this.regForm.submit(); } else { this.nullify_values(); return false; } } } 

First, reset valid values. Then we go through the form fields. If the field does not carry a special meaning (such as reset) or is not ticked - skip it. Remove leading and trailing spaces. And if the field is necessary, we check its contents using a regular expression. If not, go ahead. Now it remains to calculate the total number of fields and the number of valid fields. And if they match, then the form can be sent.
     single = null;    window.onload = function() {        var regForm = document.forms[0];        Singleton.regForm = regForm;        Singleton.regForm.onsubmit = function() {            return Singleton.submit();        };    }; 

And at the very end, we "zonet" the single object so as not to change the Singleton.fields by chance, grab the form and give it the submit event handler.

Pointy


1 . If we zanuluy single , whether we will not destroy in passing Singleton.fields ? Not. And that's why. Assigning the object to the variable fields, we do not pass the object itself, but only a reference to it. Physically, the object is stored in the so-called Memory Heap . And the garbage collector will not be removed from there as long as there is at least one link to it. Thus, we only deleted the link to the array, and the objects were not destroyed, because there is another link to them, namely Singleton.fields .

2 In the case of a large number of fields that do not require validation, will it not turn out that many objects are created, the properties of which are by and large not needed? Not. And that's why. When we retrieve the object field, the JS interpreter first looks in the object itself and if it does not, in the prototype. Thus, the default values ​​are stored in the prototype in a single copy, which is not expensive.

3 Why when the contents of a field satisfy a regular expression, do I check again? I have no clear answer to this. Experimentally, I noticed that when the RegExp.test () function is used, it first returns the expected result, and then the opposite. Try to comment out this line and see for yourself how the behavior will become unpredictable. In the usual case, this is not observed.

Tsimes


This script has great flexibility in the sense that during the transfer you will only have to change the names of the fields (the keys of the single array) and regular expressions to verify them.

View the work of the script here .

And download it here .

Afterword


So with the simplified task of checking the contents of the form, we coped. However, the following questions remain:
How to set an arbitrary style for an incorrectly filled field?
How to add validation to other events, for example, when a field check is needed as data is entered?
How to give a message that would help the user to understand what is the error?
What if there are more than one form on the page?
I will try to consider these questions in the second part of the post.

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


All Articles