Checking the correctness of filling out the js form. Ajax form validation before submitting like

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

    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 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 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 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;"; 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("!}

    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 it will display //"Specify the field value" if title is not specified var title = " field value

    Invalid field value

    "); else( if(error===false)//if $(after).after(" Specify "+title+" 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"))//look at 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

    checks, 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; 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.

    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 separate function checks 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 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.

    In our example, we have 5 fields that need to be filled in:

    - Name
    - message
    - e-mail
    - contact number
    - check number for protection

    In addition to simply checking for empty fields, we will show

    how to check if your email and phone number are entered correctly

    We will check the fields with using JavaScript. In the last field you must enter a certain number (to protect against automatic filling). If the fields are empty, an alert window will appear with a notification. TO this script We immediately added sending the completed form by email, we will do this using PHP.

    So, let's create a file index.php and write the following form there:

    1. Your name:



    2.Message:



    3. Email



    4. contact number



    3. Enter the amount 10+10





    Create a file data.js, write the verification code into it:
    function Formdata(data)(
    /* if the field Your name is not filled in, the length is less than 3-x*/
    if (data.fnm != null && data.fnm.value.length< 3)
    {
    alert("Fill in the field "Your name"");
    return false ;)

    /* if the Message field is not filled in */
    if (data.text != null && data.text.value.length< 3)
    {
    alert("Fill in the "Message" field");
    return false ;)

    /* User's e-mail */
    if(data.email != null && data.email.value.length == 0)
    {
    alert("E-Mail field is empty");
    return false ;)

    if(data.email != null && data.email.value.length< 6)
    {
    alert("E-Mail is too short");
    return false ;)

    if(!(/^w+[-_.]*w+@w+-?w+.(2,4)$/.test(data.email.value)))
    {
    alert("Enter the correct E-Mail address");
    return false ;)

    /* contact number */
    if(data.phone != null && data.phone.value.length == 0)
    {
    alert("Contact phone number field is empty");
    return false ;)

    if(data.phone != null && data.phone.value.length< 5)
    {
    alert("The "Contact phone" field must contain at least five characters");
    return false ;)

    if(!(/^+z/.test(data.phone.value+"z")))
    {
    alert("The contact number is incorrect");
    return false ;)

    /* make the amount field equal to a certain number */
    number = document.getElementById("summa");
    if (number.value !== "20")
    {
    alert("Amount was not entered or entered incorrectly");
    return false ;)
    ) Loading this file in our document, place it between head tags:

    Now our test is ready. Now, after all the data has been entered, we send our form to us by email.
    We write the php code in the index.php file:

    0

    I'm making a cross domain ajax request to my 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

    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:

      Activity

    0

    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; ) ));

    You can also do an OnKeyUp function.

    0

    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 ));

    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 .

    1

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

    If(!validateForm()) return false;

    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.

    In this article we will begin to deal with more complex and functionally complete scripts. Let's go through all the stages step by step - starting with setting the problem and ending with a universal script, ready for use. And let's start by validating the form before sending it to the server.
    General considerations and html code of the form

    Form validation is perhaps one of the most commonly used functions. It’s a rare site without any variation of it, be it a simple sending of a message by e-mail or a complex order form in an online store. The benefit of the script is obvious - to check that the user has filled out all the required fields before sending and thereby avoid the problem of receiving empty or missing emails contact information sender.

    Let's assume that we already have a form and it consists of the following 4 fields: name, email address, the subject of the message and the message itself. The corresponding html code for such a form would look something like this:


    < form action = "/cgi-bin/formmail.cgi" onsubmit = "return sendform();" >

    Your name : *< input type = "text" name = "name" >< 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 regular form directly in the tag we monitor the onsubmit event and when it occurs, we call the form verification function sendform().

    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 javascript support is disabled in the browser, 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 put 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 boolean values: true or false. And, depending on this value, the form will either be submitted or not.

    Now let's try to write check 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 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 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 = 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 :)