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 problem

Doing 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.

Analysis of inspection options.

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.
Of course, the field can be either mandatory or optional. A situation is possible when a field is optional, but since you are filling it out, do it not anyhow, but according to a certain rule.

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.

Organizing the storage of information about the fields being checked and types of verification. Let's say we need to check the following input for an email:

In my opinion, there are only two storage options here:

  • We create a javascript object in which we store the fields necessary for verification.
  • We insert information about checks directly into field tags.
  • 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:

    titleIt 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_checkThe verification flag is what we will use to search for the fields being checked. And it can take the following values:
    • Y means you need to check
    • email or num – means standard check by email or numbers/phone if full
    • Y_email / Y_num – mandatory verification for email or num
    • groupID(Y) – enclosing an element in a group with identifier groupID with verification parameters specified in parentheses
    cfm_confirminfoBy 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_functionIn order not to complicate the overloaded cfm_check, here we will write the name of the non-standard field checking function
    Script for checking fields are complete.

    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 examples

    Firstly 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:

  • In the html markup for required fields, a data attribute is added, which is a mandatory marker.
  • Validation is performed only for those fields that have this attribute.
  • The ability to expand functionality by checking the value specified by the user in the field.
  • 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
    When adding a form to a site, for example, a form feedback, it is often necessary to check all or some fields before sending to ensure they are complete. Theoretically this can be done using PHP, however using JavaScript allows you to unload the server script by transferring all the action directly to the user’s browser.

    Let's assume that we have a small form consisting of two inputs (text and password), a textarea and a submit button. Our task is to check that the first two input and textarea are empty immediately before submitting the form. If there are no empty fields, then the form should be submitted. If there are empty fields, you need to surround them with a red frame, display a message in the form of an alert stating that all fields must be filled in, and then disable submitting the form. After the user removes the alert, the color of the field frame should return to its original state. The website of Zheka Nesmelov will help you to beautifully design the form itself.

    In order for everything to work as it should, we will bind the value returned by the send() function to the onsubmit event of the form. This function will return true or false depending on whether all fields are filled in. If false is returned, then when the button is clicked, the form will not be submitted, if true, then the form will be submitted. Note that we are not giving the fields an id (this would make them much easier to hook through the JavaScript DOM).

    Checking the completion of form fields in JavaScript

    Now let's move on to the JavaScript code. There will be two functions here. The first send() function does the actual checking. By the value of the valid variable, we will understand whether all fields are filled in after the check is completed. In elems we place all the elements of the first form (index = 0) of our document. Instead of 0, you can use, for example, the name of the form as a string (if it is specified). Next in the loop we go through all the elements of this form, simultaneously checking whether the current element is textarea or input with type = text || password. If so, then check the value of this element. After all, value will contain the text entered by the user. If value = to an empty string, then assign element's border red color, and set the valid variable to false. At the very end, after passing through all the elements, we check valid. If it is false, we display an alert, disable form submission, and highlight in red only those fields that are not filled in. Otherwise, submit the form.

    The second function in the JavaScript code will be executed immediately after the document is loaded. When you hover the mouse over the form (the onmouseover event), the loop will begin to iterate through all its elements. If any of the elements border CSS property= "2px solid red", then it is assigned the default value (the red color is removed).

    That's all. All that remains is to decorate your form beautifully!


    Leave a comment, click “Like” (“Like”) and “Save”, and I will write something else interesting for you :)





    

    2024 gtavrl.ru.