Javascript validation of form fields before submitting. Form Validation in JavaScript
We've all filled out forms at some point. Some even processed the results they collected, be it orders placed in an online store or return service. When asking the user to fill out some information, we want it to conform to a certain format, especially if it is later processed by a CMS like 1C bitrix, WorldPress, and so on. After all, if in the telephone column the user for some reason writes down his Skype login, a data processing error may occur: it will not be recorded, and the user will be thrown back to the form filling page. Consequently, the question arises of how to check the entered data online and prevent the sending of incorrect data.
The work of the described solution, developed by us, can be immediately assessed using the example of the ordering procedure on the Newcom website. Below we will begin a story about the process of its development, as well as give a few more examples.
Formulation of the problemDoing a simple javascript check of the form fields before sending it to the server takes a couple of minutes. Only when you write this simple thing for the tenth time for just one site, you involuntarily think about automating this process. At some point, thoughts about this became so obsessive that I had to sit down and create a miniature library that dealt with the fields.
If you break the problem into blocks, you get something like the following diagram:
Well, if there is a scheme, then let’s implement it.
What fields are most common on forms?
- Text inputs, which, as a rule, are checked either simply for completeness or for simple regular expressions like email or phone.
- Checkboxes checked for the presence of a mark (like an agreement for the processing of personal data).
- We can also mention drop-down lists that are checked for some non-empty value.
- Don't forget about the insidious radio buttons. Why insidious? There are pitfalls in checking for marks.
Since we have set out to write a more or less universal script, we need to think about perverted unusual structures, which will be called “groups” in the future. By this word we mean fields connected to each other. For example, if the user has checked the “Send news by email” checkbox, the “e-mail” item becomes mandatory to fill out, or they often like to divide the phone number into a code and the number itself - then the correctness must be checked in all fields, and the incorrectness of one entails an error in both. And the error message should not be displayed for all fields of the group, but only for one, otherwise the number of them will start to dazzle your eyes.
What conclusion can be drawn?
It is necessary to organize a regular check for a text field, a check for email and “digital” fields like phone number, age, etc. Checkboxes and radio buttons are checked by the checked property, drop-down lists are checked by value. To satisfy cunning groups, write a handler for them too. In addition, provide the ability to check some fields with some custom function for particularly confusing cases.
In my opinion, there are only two storage options here:
A JS object will work faster and look much more correct than some non-standard attributes in tags. Let's say it will look like this:
Var checkThis=( handle: "$("")",//pointer to the field being checked type: "email",//check type: regular, email, number title:"enter your email here, for example",//hint about error nesess: true,//required flag group: false,//group pointer); var AllChecks=;//and this is an array where all checked objects would be stored
If the programmer gets to the site when it is already completely laid out (that is, the action takes place in a science fiction novel) - this approach is excellent. But often something will definitely need to be completed, including adding additional fields or creating new forms, and leaving the addition of field handlers to the conscience of the layout designers, even if you have a written constructor, means dooming yourself to constant requests from them in the “a” style Everything’s broken here.” And then you will have to forget about the main postulate of the idea, automation (well, more precisely, ridding yourself, your loved one, of unnecessary body movements).
Then you can try stuffing verification data into non-standard attributes, turning the laconic
into a bulky monster like We will focus on this option. We are for versatility.Then we enter the following processed tags:
title | It is, of course, standard, but here we will write a message about the erroneous filling of the field. And we will display it in the style “Specify”+title |
cfm_check | The verification flag is what we will use to search for the fields being checked. And it can take the following values:
|
cfm_confirminfo | By default, errors will be displayed immediately after the element being checked, which is not always convenient. So let us indicate in this attribute the jq selector to the element after which the error will be displayed. For example, cfm_confirminfo=’#placeForErrors’ |
cfm_function | In order not to complicate the overloaded cfm_check, here we will write the name of the non-standard field checking function |
We have received the information, all that remains is to process it. The algorithm here is not complicated:
- At the input we provide a pointer to the form in which to perform the check (we can have many forms on the page!);
- we go through the specified form elements, checking that they are filled out correctly;
- if there are errors, we mark them; if not, we allow the form to be validated.
Perhaps it’s time to produce js code that implements the functionality at least partially, since such a bunch of text has already been written down?
If(typeof cFM_classError === "undefined")//here we write the css class assigned to the wrong fields var cFM_classError="cFM_wrong"; function cFM_checktrueAttr(parent)//prepares data for processing //(parent is a jq-pointer to the form, or a combining block) ( var error=true; //clean up after the previously called function $("div."+cFM_classError).remove ();//remove hints $("."+cFM_classError).each(function())(//remove error highlighting $(this).removeClass(cFM_classError); )); //look for fields to check var inputsToHandle=false ; if(typeof parent !== "undefined") inputsToHandle=parent.find(""); else inputsToHandle=$("");//well, if the parent is not specified, let's check everything //grab the found elements and observe them inputsToHandle.each(function())( if(error) error=cFM_prepareChecking(this);//check objects, look for at least a single error else cFM_prepareChecking(this); )); return error;//return true if all elements passed an error, and false if someone failed) function cFM_prepareChecking(handle)// starts checking a specific element and marks erroneous ones ( var error=true;/*return value; the meaning is simply to show that there is an error takes the value: true - no errors; false - field is not filled in; "wrong" - the field is filled in incorrectly;*/ //determine the signature of the field if an error is detected in it. By default, //"Specify the field value" will be displayed if title is not specified var title = " field value"; if(typeof $(handle).attr("title") !== "undefined" && $(handle).attr("title").length>0) title=$(handle).attr("title"); var after = handle;//куда лепить сообщение об ошибке var attribute = $(handle).attr("cFM_check");//значение великого атрибута cFM_check //а не задали ли какую хитрую функцию для проверки поля? if(typeof $(handle).attr("cFM_function") !== "undefined") var chkFunk=$(handle).attr("cFM_function"); //наконец, проверяем поле if(typeof chkFunk !== "undefined") error=window($(handle)); else error=cFM_checkFullness(handle); //коль ошибка закралась к нам if(error!==true) { //определяем, куда лепим сообщение об ошибке if(typeof $(handle).attr("cFM_confirmInfo") !== "undefined") { after=$(handle).attr("cFM_confirmInfo"); if(after.indexOf("self")===0)//если вдруг селфы непойми зачем прилепили after=after.substr(4); } if(error==="wrong")//коль поле заполнено неправильно $(after).after("!}
Invalid field value
"); else( if(error===false)//if $(after).after("
Specify "+title+"
");//html errors else//if special check with special html $(after).after(""); ) $(handle).addClass(cFM_classError);//adding an error class if($(handle). attr("type")=="radio")//we are finalizing the radio buttons $("").addClass(cFM_classError); error=false; ) return error; ) function cFM_checkFullness(handle)//and this standard function checks ( var error = true; //read data from attributes var attribute = $(handle).attr("cFM_check"); //required flag var required = true; if(attribute.indexOf("Y")=== -1) required=false; //check for format var format=attribute; if(required) format=attribute.substr(2); switch($(handle).attr("type"))//let's see what We have this for the element ( case "checkbox": if(!$(handle).prop("checked")) error=false; break; case "radio"://promised problem with radio if(!$(handle) .prop("checked") && $(":checked").length==0) error=false; else error=true; break; //both text, and select, and textarea are identical here default: if(($ (handle).val().trim().length==0 || $(handle).val()=="0") && required) error=false; else ( if(format==="num" )//check for a number ( var regCheck = new RegExp("[^0-9\s-]+"); if(regCheck.test($(handle).val())) error="wrong"; ) if(format==="email")//check for email ( var regCheck = new RegExp("^(+[-._+&])*+@([-0-9a-zA-Z] +[.])+(2,6)$"); if(!regCheck.test($(handle).val())) error="wrong"; ) ) break; ) return error; )
As an example, we will also give a special checking function, for example, checking for the presence of two words in the input (First Name, Last Name or First Name, Last Name). The input that triggers the check for this function is implemented as follows:
And the check function will look, for example, like this: function checkName(handle) ( var handleValue=handle.val().trim(); //as practice shows, users do anything to separate their first name from their last name if(handleValue.indexOf( " ")!==-1 || handleValue.indexOf(",")!==-1 || handleValue.indexOf(".")!==-1) return true; else return false; ) What a style We should set some of our checks: div.cFM_wrong ( color:red; font-size:10px; position:absolute; width:140px; ) input.cFM_wrong( background: #ffd9d9; border-color:#d3adad; ) Script form validation.Now in case successful implementation function cFM_checkFullness() (that is, returning true), the script must send the form for processing. How to implement this depends on the specific form. If confirmation for submission comes through the submit button, then you can subscribe to the form submission event (onsubmit) and, depending on the result of the check, send it or not. For example, like this:
and here, like, a bunch of form tags. If the sending is done using ajax, then everything is simple: call it depending on the result of the function cFM_checktrueAttr($(this)); Additional troubles.In the above code there is no check for groups (because the cumbersomeness of the code increases significantly, and the size of the scrollbar of this article probably scared off many visitors). The differences in the algorithm will be insignificant: checking elements by group should be launched in a separate block, and depending on the operation of the entire block, an error message will be displayed in a specific element.
True, at this point it’s worth slowing down and thinking: is it really necessary to modify the code to support groups, or can we limit ourselves to writing a separate verification function for a couple of complex fields?
What do we have in the end? By connecting a couple of files (.js and .css), we get property checking functionality that you can throw on any sites with peace of mind, provided jquery is connected. After all, it’s much nicer to have a set of ready-made tools at hand than to spend a lot of time producing them before each task of the same type.
Connection and examplesFirstly we need jquery library. You can download it, for example, from the official website.
Or simply insert the line into the header (what’s inside the tag) of your site
Then download (right click -> the item you like with the word “save”) from here the file with the js code and, if necessary, a file with css styles for erroneous fields from here.
We add them to the header too: Now you need to arrange the attributes of the form fields according to, depending on what kind of check you want to perform.
The final touch is to add the onsubmit event tag: “onsubmit="return cFM_checktrueAttr($(this));"".
Let's now try to implement a check of such a simple form.
cheerful mustache May 7, 2017 at 02:32 Checking empty form fields: a universal method- HTML,
- JavaScript
Those who create websites at some point are faced with the need to check whether the user has filled out the fields of a form posted on the site. For this purpose, some kind of option for checking empty fields is created, which is used in its projects. But for each case, the number of fields that need to be checked may be different. This leads to the fact that the created verification option must be changed depending on specific conditions, and in the future we will have several modifications of it.
In addition, several forms can be placed on one page of the site, each of which will have a different number of required fields. As a result, the code will include several blocks with the same functions, but different conditions, which is not always the right decision.
In my practice I also had to use different variants checking the completion of form fields depending on specific conditions. And the *.js file contained several functions for checking different forms, which increased the amount of code and worsened its perception.
At some point it was decided to write a version universal method checking for empty fields, which can be used for any form with any number of required fields. Necessary conditions This method was determined by the simplicity and absence of bulky structures. As a result, a method was found that completely satisfied me with both its simplicity and versatility.
The essence of this method:
Example of form markup:
Form Heading #1 Required Required Required Required
Example field validation code:
$(".js-form-validate").submit(function () ( var form = $(this); var field = ; form.find("input").each(function () ( field.push(" input"); var value = $(this).val(), line = $(this).closest(".some-form__line"); for(var i=0;i< br >
Email address: *< input type = "text" name = "email" >< br >
Message subject :< input type = "text" name = "subject" >< br >
Message :< textarea name = "message" >< br >< br >
<
input type
=
"submit"
value
=
"Send"
>
<
input type
=
"reset"
value
=
"Clear"
>
* - required fields to fill in
Note that, unlike a regular form, we track the onsubmit event directly in the tag and when it occurs, we call the sendform() form validation function.
Why was this method of calling the function chosen? After all, it was possible to apply, for example, the onclick event? The answer is simple - when used onclick events The "submit" button will have to be replaced with a regular button. And, if the browser is disabled javascript support, we will not be able to submit the form (!). Tracking the onsubmit event does not have this drawback, because even with script support disabled, the form will be submitted.
If you take a close look at the html code of our form, you will notice that I placed an asterisk next to these fields, and placed a footnote at the end of the form. This was done, of course, for convenience and basic respect for the user.
Function to validate the form before submitting
Now let's move on to the main thing - to writing the very function that will directly check the form. Let's think about what we need from her? Well, firstly, check that the required fields are filled in, and secondly, send the form. If several of the required fields are empty, we need to generate a message about this to the user and move the cursor to the corresponding element.
First, let's write the general binding of the function:
<
script language
=
"javascript"
>
The method we used to call a function through the onsubmit event requires the return of one of the logical values: true or false as the result of the function. And, depending on this value, the form will either be submitted or not.
Now let's try to write a verification function tied to this specific form. As you remember, we only have two fields required to fill out: the visitor’s name and his email address. The simplest thing is to check the contents of each of the required fields for absence of text:
<
script language
=
"javascript"
>
As you can see, the verification function consists of two identical blocks, differing only in the name of the field being checked. Let's comment out each line in these blocks:
First we check that this field is empty. And if this is so, then
display an error message using the built-in alert() function. After the user closes the window, we
Let's use the focus() method and move the cursor to the erroneous field. And finally
Let's exit the function by setting the success flag to false.
If the field being checked was not empty, then the corresponding block is simply skipped. If all check blocks are skipped, the function returns true as a result, which indicates a successful check.
Universal verification function
If we need to check only two or three fields, then we can still put up with this method of checking “one by one”, but what if there are several dozen of them? But this is not uncommon - especially in complex questionnaires. Therefore, we slightly modify our function so that it does not depend on the number of fields being checked.
First of all, we will create an array where we list the names of all the fields that require verification:
Required = new array("name", "email");
This approach will allow us to very easily add and modify the list of required fields without directly changing the code of the function itself.
In addition to the array described above, we will add another one, which will contain the error text for a specific field:
Required_show = new array("Your name", "email");
This will allow us to freely vary the text about errors and use the Russian language correctly, and not be content with indigestible phrases like “name not entered.”
Having an array of required fields, the entire check can be done in a loop. This is what the modified check function would look like:
<
script language
=
"javascript"
>
In the loop, all form fields are checked to see if they match the “required” fields. If a match occurs, the check is carried out in the same way as described above, but with one caveat - the introduction of an array with error messages required a slight modification of the alert() function, so now the error text directly depends on the field name.
That's basically it. This function is quite universal and with minimal adjustments (essentially the contents of two arrays) can be adapted to any form.
Back |