JavaScript form validation. Validation of entered data using JavaScript, sending the completed form by email

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 of some kind custom function for especially difficult 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 additions to additional fields

    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 check by 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 run through specified elements forms, 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 the 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 the check 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; "wrong" - field is filled incorrectly;*/ //determined with 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 //а не задали ли какую !} tricky function to check the field?

    if(typeof $(handle).attr("cFM_function") !== "undefined") var chkFunk=$(handle).attr("cFM_function");

    //finally, check the field if(typeof chkFunk !== "undefined") error=window($(handle));

    else error=cFM_checkFullness(handle);

    ");//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)//this is 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"))//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; //both text, 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 also give

    special function

    Now, if the cFM_checkFullness() function successfully completes (that is, returns true), the script should 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 in groups should be launched in a separate block, and depending on the operation of the entire block, an error message should 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 connected jquery. 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 key-> favorite item with the word “save”) from here is a file with 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.

    Very often there is a need to add a form to the site, because the form is the most popular way communication between the user and the site, and it is very important that the data entered by the user is correct. And in order for the form to be sent with the correct data, it must be checked before doing so. And so we will deal with form validation in JavaScript in this article.

    Let's first create a form that we will then check:


    Your name:



    Your password:



    What's your gender:




    Select number:

    1
    2
    3



    Your message:



    Agree with our rules:




    Upload file:







    This is the form. I hope that you are familiar with HTML and I think it costs nothing to explain. If something is not clear, then look at how this code works in the browser.

    Now let's talk about how to get values ​​from form fields. After all, before checking them, you need to find out what the user wrote there. General form to access the form field like this:

    Document.form_name.field_name.value;

    That is, we first access the Document object, then its Form property (via the form name), then the name of the field of this form, and, finally, the value of the field. Let's output all the fields that obey this general view:

    Var form = document.form1;
    document.write(form.firstname.value + "
    ");
    document.write(form.pass.value + "
    ");
    document.write(form.number.value + "
    ");
    document.write(form.message.value + "
    ");
    document.write(form.rules.value + "
    ");
    document.write(form.hidefield.value + "
    ");
    document.write(form.fileupload.value + "
    ");
    document.write(form.sub.value + "
    ");
    document.write(form.but.value + "
    ");

    These are all fields that have a value property and can be accessed this way.

    Now let's talk about one special form element - radio. Let's access the radio value:

    Var sex = (document.form1.sex.checked)?
    document.form1.sex.value: document.form1.sex.value;

    Notice that we have two radio elements that are in the sex array. Their indices are 0 and 1. IN this script we check if our first element is included ( checked), then we assign the value of the first element, otherwise we assign the value of the second element. By the way, if anyone doesn’t understand, this is a construction of the IF condition operator. Of course, one could write it like this:

    Var sex;
    if (document.form1.sex.checked) sex = document.form1.sex.value;
    else sex = document.form1.sex.value;

    Now that we have access to all the fields, let's finally validate the form. But first, let's add the "onSubmit" attribute to the tag with the value "return check(); ". This attribute will do the following: before submitting the form, call a function that should return either true or false. If it returns true , then the form will be sent to the server, and if false , then the form will not be submitted.

    Now let's create a check() function, which should, firstly, check the entire form, inform the user about errors, and also return true (if the form is completely correct) or false (if the form contains errors).

    Function check(form) (
    var firstname = form.firstname.value;
    var pass = form.pass.value;
    var message = form.message.value;
    var rules = form.rules.value;
    var file = form.fileupload.value;
    var bad = "";
    if (firstname.length< 3)
    bad += "Name is too short" + "\n";
    if (firstname.length > 32)
    bad += "Name is too long" + "\n";
    if (pass.length< 3)
    bad += "Password is too short" + "\n";
    if (pass.length > 32)
    bad += "Password is too long" + "\n";
    if (message.length< 3)
    bad += "Message too short" + "\n";
    if (rules != "on")
    bad += "You did not agree with the rules" + "\n";
    if (file.length == 0)
    bad += "You have not selected a file to upload" + "\n";
    if (bad != "") (
    bad = "The form is filled out incorrectly:" + "\n" + bad;
    alert(bad);
    return false;
    }
    return true;
    }

    In this script, we first get all the data that needs to be checked and write it into variables. Then we create a variable bad , into which we write all incorrect data. Then there is a whole set of IFs that check the fields in the form and write any errors to the bad variable. Then, if the bad variable is not empty (that is, there were errors), then we display a window (alert()) with errors. And we return false so that the form is not submitted. If the bad variable is empty, then we simply return true so that the form is sent for processing to “handler.php”.

    0

    I'm making a cross request ajax domain to your php page on the server. I am submitting a form from html via ajax to mine php page on server. Problems with client-side validation.

    I don't know how to do client side validation before submitting the form.

    HTML form standard form, placement of input fields: first name, last name, message.... My HTML form, on the client side:

    var output = $(".nesa"); $(document).ready(function())( $("#form1").submit(function (e) ( e.preventDefault(); $.ajax(( url: "http://www.example.com/ form.php", crossDomain: true, //set as a cross domain requests type: "post", data: $("#form1").serialize(), beforeSend: function())( // add spinner $(" .spinner").append("

    "); ), success: function (data) ( $(".nesa").html(data); alert("sent " + data); ), error: function())( output.text("Message is not sent!"); ) )); )); ));

    How is validation? I'm trying to put code in sendmail but have no luck. Or is it possible to use submitHandler? The idea is when the user clicks the "Submit" button, this check runs and if the "paste address" fails Email

    " Now when I click the submit button, you send the data to the server. I want the first input fields to be validated.

    This form is the actual work of submitting data to the server, but just needs to figure out how to do the validation. Where to put validation in an ajax call?

    • Thanks to
    • 5 answers

      Sorting:

    0

    Activity Please confirm the form before submitting AJAX request

    . If there is no error then the ajax request should be sent, otherwise return false. You can do this:

    $("#form1").submit(function (e) ( e.preventDefault(); // Get the Login Name value and trim it var name = $.trim($("#name").val()) ; // Check if empty of not if (name === "") ( alert("Text-field is empty."); return false; ) ));

    0

    You can also do an OnKeyUp function.

    First, are you actually using an AJAX form?

    You explained that you are loading the form via AJAX, but are you submitting it the same way? It seems to me that you are trying to send HTML code. You can connect to the submit button click event before submitting the form. However, since the button is added to the page at runtime, you need to register an event on document .

    $(document).on("click", "input", function() ( // Validate form // Add error message on fail, and return // Else submit form via AJAX ));

    1

    Anyway, you can use jQuery's blur event as an alternative to check each field when the user moves on to the next one. You can even check every time the user presses a key with keypress .

    Create a function to validate a form that returns true/false. Call the function just before $.ajax. check if return is false then return.. see example below...

    0

    I always check them right before I enter them into the AJAX call. Here's my exam

    $("#form_nieuwsbrief").bind("submit",function())( var name = $("input").val(); var email = $("input").val(); var proceed = true ; if (name=="")( $("input").css(("border":"2px solid red")); proceed = false; ) if (email=="")( $("input ").css(("border":"2px solid red")); proceed = false; ) if(proceed == false)( $("#msg").append("U bent informatie vergeten in te vullen. "); setTimeout(function())( $(".alert").fadeOut(400, function())( $(this).remove(); )) ;),10000); ) if(proceed == true) ( // make the ajax call

    It's just a newsletter that simply asks for a name and email address. But the principle is the same. Before making the ajax call, create an if else statement with the variable you set if something is false. otherwise you will stick to his initial check so you can continue.

    “Fool protection” is a set of measures to prevent the entry of incorrect information into a form. For example, if you need to enter in a field positive number from 0 to 10, then you should check that the user has not entered text or a number that does not lie in the specified range, i.e. the number should not be less than zero and more than ten.

    Why is incorrect information being entered? This is mainly done for three reasons.

  • The user accidentally made a mistake, for example, he inattentively read what he was required to indicate.
  • The web page asks for data in an ambiguous manner, leaving the user guessing and guessing what they really want. However, the opinions of the developer and the user do not always coincide.
  • There are a number of people who perceive instructions as a challenge and try to do the opposite. Such users reason something like this: “Yeah, they’re asking me to enter a number. What will happen if I indicate the letters?” Then they ask obviously incorrect information and see what it leads to.
  • It should be understood that precise and correct wording, although it reduces the likelihood of errors, does not in any way save you from them. Only technical means on the server side allow you to get the required result and avoid entering incorrect information. However, revision or, as it is also called, client-side validation allows you to quickly check the data entered by the user for correctness, without sending the form to the server. This saves user time and reduces the load on the server. From a usability standpoint, there are also advantages - the user immediately receives a message about what information he entered incorrectly and can correct his mistake.

    Obligatory field

    Some form fields must be completed before they are sent to the server. This, for example, applies to the registration form, where you are required to enter a login and password. Used to specify required fields required attribute, as shown in example 1.

    Example 1. The required attribute

    HTML5 IE 10+ Cr Op Sa Fx

    Obligatory field

    Login:

    Password:

    Required fields must be filled in before submitting the form, otherwise the form will not be sent to the server and the browser will issue a warning about this. The type of message depends on the browser, for example Chrome displays a tooltip as shown in Fig. 1.

    Rice. 1. Required field is not filled in

    Data correctness

    Initially, there are two fields in which user input is checked automatically. This is a web address and an email address. Chrome browser also checks the calendar data field for validity, but only because it does not have a mouse-click calendar selection interface. The following rules apply to these elements.

    • The web address ( ) must contain the protocol (http://, https://, ftp://).
    • The email address ( ) must contain letters or numbers before the @ symbol, after it, then a period and a top-level domain.

    Browsers have slightly different policies for verifying user data. For example, Opera substitutes http protocol:// before the entered text automatically, whereas other browsers expect it from the user. Chrome and Opera require that postal address there was a point, it is not required for Firefox.

    Example 2 shows a form with required fields in which two fields are validated by the browser.

    Example 2: Data Correctness

    HTML5 IE 10+ Cr Op Sa Fx

    Data correctness

    Fill out the form (all fields are required)

    Name:

    Email:

    Website:

    Opera only checks a form element if it has a name attribute.

    What happens in Opera when you enter incorrect data is shown in Fig. 2.

    Rice. 2. Warning about incorrect data

    Input template

    Some data cannot be classified into one of the form element types, so you must use a text field for it. In this case, they are entered according to a certain standard. So, the IP address contains four numbers separated by a dot (192.168.0.1), postcode Russia is limited to six digits (124007), the phone contains an area code and a specific number of digits, often separated by a hyphen (391 555-341-42), etc. The browser must specify an input template so that it checks the data entered by the user according to it. To do this, the pattern attribute is used, and its value is a regular expression. Some typical values ​​are listed in table. 1.

    Example 3 asks you to enter hexadecimal value color (#ffcc00) and if it is not in this range, the browser displays an error message.

    Example 3. Input template

    HTML5 IE 10+ Cr Op Sa Fx

    Color input

    Enter the hexadecimal color value (must start with #)

    In Fig. Figure 3 shows a warning in the Chrome browser.

    Rice. 3. The entered data does not match the template

    Unvalidation

    Validation is not always required for a form; for example, a developer might want to use universal solution in JavaScript and it no longer needs duplicate checking by the browser. In such cases, you need to disable built-in validation. To do this, use the novalidate attribute of the tag. Example 4 shows the use of this attribute.

    Example 4: Unvalidation

    HTML5 IE 10+ Cr Op Sa Fx

    novalidate attribute

    For a similar purpose, the formnovalidate attribute is used, which is added to the button for submitting the form, in in this case to tag. In this case, the form from example 4 will look like this.

    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 empty fields will be, then you need to circle them with a red frame, display a message in the form of an alert stating that you need to fill in all the fields, and then disable submitting the form. After the user removes the alert, the border color of the fields should return to 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 = empty line, then we 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 :)