Jquery validate js dynamic definition of rules. Examples of form validation using JQuery


Client-side field validation is something that every form should have, there is no doubt about it. Firstly, the user does not need to wait and waste his nerves. Secondly, you show that you care about your visitors. It is very nice for the visitor to know in advance what he did wrong.

In this tutorial, we will learn how to write jQuery form validation in real time. If you want to see what you can come up with, you can click DEMO and take a look.

What will we learn today? How do we implement jquery validation?

There are many ways to achieve this, here are the most common ones:

  • We can create a SPAN tag (which will contain validation information) next to the input field, and give it a specific ID through which we will access it.
  • We can wrap each field in a P tag, inside which we create a SPAN that will contain information about the field's validation.
  • You can also wrap the P field with a tag, inside which you can “learn” SPAN (on the fly using jquery).
  • This will all work, but it is not the best way to implement it. Why? Because there is too much extra HTML code in the input form that we don’t need. Must be observed.

    We'll do it the way I did it for myself. In my opinion, this is the most correct solution, although no one does this. Honestly, I haven't seen anyone else do this... if you know, write me a comment at the end of the lesson.

    What are we going to do?
  • We will write simple form, beautiful and with clean semantic code, without unnecessary tags.
  • Since people fill out each field individually, we can track and validate it on the fly:
    • Determine its position in the window (upper left corner)
    • Determine its width
    • This way we will know where its end is.
    • Let's add validation information in a DIV block with a specific ID, to the right of a specific field. We will also assign the corresponding classes .correct or .incorrect.
  • Note: this is also acceptable for people not using JavaScript in their browser. These will be validated on the server side.

    Project structure

    We will need to create three files:

  • index.html
  • style.css
  • validate.js
  • We will look at everything step by step... first the HTML code, then the necessary CSS styles, later we will focus on the main jQuery form validation script.

    Writing HTML

    Let's break it all down...

    Step 1 - create basic HTML code

    To get started, create an index.html file and paste this basic code into it. You see that we are connecting jQuery file at the bottom, before validation.js, which contains our validation script.

    Step 2 - create a shape divided into three parts

    We'll create a three-part form to see how to validate different input fields and checkers. For division we use FIELDSET and LABEL, for the headings of each section:

  • Personal information (username, birthday, gender, vehicle).
  • Email (user email input field).
  • About Me ( brief information about the user).
  • Real-Time Form Validation Using jQuery Personal Info Email About You Step 3 - add fields and confirm button

    Great, now let's create some input fields for our form. For our lesson, we specifically selected several different fields:

    • Three INPUT fields (username, date of birth, email address).
    • RADIO buttons to select gender.
    • CHECKBOX for Vehicle user.
    • TEXTAREA for user information.
    • BUTTON for the “Confirm” button.

    We will wrap each LABLE and input field in a P tag to separate it into separate blocks. Your final index.html file will now look like this:

    Real-Time Form Validation Using jQuery Personal Info

    Full name:

    Day of birth (dd-mm-yyyy):

    I am: Man Woman

    I own: car airplane bicycle ship

    Email

    Email ( [email protected]):

    About You

    Tell us a little bit about yourself:

    submit

    This may look a little scary, but that's because there are a lot of input fields in our form. In fact, there is nothing complicated here. Save your file and look in your browser to see what happens. Now let's decorate a little...

    Adding CSS

    Since CSS styling is not the main topic of today's tutorial, we won't dwell on it. We just need this CSS code to make the form look nice and all the blocks to be in place.

    Create a style.css file and paste the code below into it. Now the form with future jquery validation looks amazing. Is not it?

    Body ( background: #efefef; margin: 0; padding: 0; border: none; text-align: center; font: normal 13px Georgia, "Times New Roman", Times, serif; color: #222; ) #content ( width: 500px; margin: 0 auto; margin-bottom: 25px; padding: 0; text-align: left; ) fieldset ( margin-top: 25px; padding: 15px; border: 1px solid #d1d1d1; -webkit-border- radius: 7px; -moz-border-radius: 7px; border-radius: 7px; ) fieldset legend ( font: normal 30px Verdana, Arial, Helvetica, sans-serif; text-shadow: 0 1px 1px #fff; letter-spacing : -1px; color: #273953; ) input, textarea ( padding: 3px; ) label ( cursor: pointer; ) .block ( display: block; ) small ( letter-spacing: 1px; font-size: 11px; font- style: italic; color: #9e9e9e; ) .info ( text-align: left; padding: 5px; font-size: 11px; color: #fff; position: absolute; display: none; -webkit-border-radius: 5px ; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: -1px 1px 2px #a9a9a9; -moz-box-shadow: -1px 1px 2px #a9a9a9; box-shadow: -1px 1px 2px #a9a9a9; ) .error ( background: #f60000; border: 3px solid #d50000; ) .correct ( background: #56d800; border: 3px solid #008000; ) .wrong ( font-weight: bold; color: #e90000; ) .normal ( font-weight: normal; color: #222; ) #send ( background: #3f5a81; width: 100%; border: 5px solid #0F1620; font: bold 30px Verdana, sans-serif; color: #fafafa; text- shadow: 1px 1px 1px #0F1620; -webkit-border-radius: 7px; -moz-border-radius: 7px; border-radius: 7px; ) #send:hover ( background: #4d76b1; border: 5px solid #253750; color: #fff; ) #send:active ( text-indent: -10px; )

    Writing jQuery form validation

    This is the most interesting and exciting part of the lesson. But first, we need to think and describe the main points of our work. You need to plan everything.

    Are planning

    Before we write, ask yourself three questions:

  • What do we need from this script?
  • How do we want to do this?
  • How will we achieve this?
  • This is clear, we want the script to validate the form. But how? We want it to do this in real time (when the user finishes filling out the input field) and when the "Confirm" button is clicked. Therefore, we will have to write several functions: separately for each input field and for all forms (which will be called when the “Confirm” button is clicked).

    To prevent code repetition, we will need to create JavaScript object for this.

    What do we need for this?

    The JS object in our case will be called jVal, it will contain the following methods:

    • jVal.fullName
    • jVal.birthDate
    • jVal.gender
    • jVal.vehicle
    • jVal.email
    • jVal.about

    The variable that will contain the status of the current error is jVal.errors. And a method that checks if any errors exist and confirms the form submission or rejects it. If any errors are found, it directs the user to the beginning of the form, where he can fill out all the fields correctly.

    The method is called - jVal.sendIt

    Now, we can start developing a jQuery form validation script. Once we write the first method, then everything will go easier and faster.

    Let's start work

    The basis of the code is simple, absolutely all jquery code will be contained within this syntax:

    $(document).ready(function())( jVal = ( ); ));

    Username Field Validation

    Our first method will process the "username" field. Paste it inside the jVal object, as shown in the example:

    Var jVal = ( "fullName" : function() ( ) );

    Now let's write a few lines of code inside the method. Just paste them in and we'll look at what that means next:

    $("body").append(""); var nameInfo = $("#nameInfo"); var ele = $("#fullname"); var pos = ele.offset();

    Line 1: We add a DIV block to the document. Class info, gives some style to the block, which is defined in the style.css file, also makes it invisible using display:none; Find an ID, this is in order to have fast access to this block and manipulate it using jQuery. This DIV block will contain field validation information.

    Line 3: We write a call to this block in a variable, since we will use it a large number of once.

    Line 4: Just like in the previous case, we record the connection to the fullname field in a variable. We will also use it many times.

    jQuery offset() function returns current position element in relation to the document. Returned as an object that contains the top and left properties. We use this function on ele to determine the position of the input field.

    Now let's add a few more lines...

    NameInfo.css(( top: pos.top-3, left: pos.left+ele.width()+15 ));

    As you can see, we are starting to operate with the styles of the nameInfo block. Specifically, we set its position to the right of the input field. To do this, we move it up 3 pixels (2nd line of code), and move it 15 pixels to the right of the field (3rd line of code).

    We have written 50% of the first method, we will bring it to the end. It's time to determine how correctly the user entered the data and take action...

    If(ele.val().length< 6) { jVal.errors = true; nameInfo.removeClass("correct").addClass("error").html("← at least 6 characters").show(); ele.removeClass("normal").addClass("wrong"); } else { nameInfo.removeClass("error").addClass("correct").html("√").show(); ele.removeClass("wrong").addClass("normal"); }

    Doesn't look good? There is nothing to be afraid of...

    Line 1: We check that the name entered by the user is not less than 6 characters.

    Line 2: Set the jVal.errors variable to true because we have determined that the username is too short. We will use this further.

    Line 3: We start operating with our nameInfo element (in which we display information). First, we remove the class correct and assign the class error. Next we insert content into the nameInfo element, this is information that the name must be longer than 6 characters. And finally, we make our message visible to the user.

    Line 4: We start manipulating our ele element (username input form). We remove the normal class and assign it to wrong.

    Line 5: If the username is long enough, then...

    Line 6: We start manipulating the nameInfo element. If the class error is assigned, we remove it and assign the class correct. We insert a “bird” inside to understand that everything is OK. And display a message for the user.

    Line 7: We operate with the ele element. We remove the wrong class, if it is applied, and apply the normal class.

    We've created our first validation method! It's time to test it. We need to be sure that our method will be called when the user finishes entering their name. To implement this, we need to attach an event to an action. We will use the change() function. Paste the example code below, under the jVal object:

    $("#fullname").change(jVal.fullName);

    What this means in human language: if the user changes the value of the "Full name" field and then is done with it, the fullName method is called, which validates the field.

    Your validate.js file should now contain the following code:

    < 6) { jVal.errors = true; nameInfo.removeClass("correct").addClass("error").html("← at least 6 characters").show(); ele.removeClass("normal").addClass("wrong"); } else { nameInfo.removeClass("error").addClass("correct").html("√").show(); ele.removeClass("wrong").addClass("normal"); } } }; // bind jVal.fullName function to "Full name" form field $("#fullname").change(jVal.fullName); });

    Validation of the date of birth field

    Now everything will go faster. We just need to make a copy of the fullName method and make some changes.

    Now, copy the fullName method, paste it below and rename it birthdate. And make the following changes:

    • Wherever nameInfo appears, replace it with birthInfo
    • Instead of #fullname, use #birthday for the ele variable
    • Paste this template regular expression below is the birthInfo.css() expression:
    var patt = /^(2)\-(2)\-(4)$/i;
    • Our old if() expression should be:
    if(!patt.test(ele.val()))
    • The message for this field will be: type in date in correct format

    This is what the birthdate method should look like after making these changes:

    "birthDate" : function ()( $("body").append(""); var birthInfo = $("#birthInfo"); var ele = $("#birthday"); var pos = ele.offset( ); birthInfo.css(( top: pos.top-3, left: pos.left+ele.width()+15 )); var patt = /^(2)\-(2)\-(4)$ /i; if(!patt.test(ele.val())) ( jVal.errors = true; birthInfo.removeClass("correct").addClass("error").html("← type in date in correct format ").show(); ele.removeClass("normal").addClass("wrong"); ) else ( birthInfo.removeClass("error").addClass("correct").html("√").show (); ele.removeClass("wrong").addClass("normal"); ) )

    Using a regular expression (line 14), we check that the date is in the format 03/28/1987. In line 16, we check that the user's date of birth matches the regular expression pattern.

    And of course, we need to attach a change() event to the date of birth field:

    $("#birthday").change(jVal.birthDate);

    Now we have another working jQuery form validation method. Great job!

    Validation of the field become

    Again, copy the fullName method, rename it gender and make the following changes:

    • Rename all nameInfo to genderInfo
    • Instead of #fullname, use #woman for the ele variable
    • In the genderInfo.css() expression, change the top variable to top: pos.top-10, and left to left: pos.left+ele.width()+60
    • Our if() statement should be:
    if($("input:checked").length === 0)
    • The message to the user will be: are you a man or a woman?

    This is what the gender method should look like after the changes:

    "gender" : function ()( $("body").append(""); var genderInfo = $("#genderInfo"); var ele = $("#woman"); var pos = ele.offset( ); genderInfo.css(( top: pos.top-10, left: pos.left+ele.width()+60 )); if($("input:checked").length === 0) ( jVal .errors = true; genderInfo.removeClass("correct").addClass("error").html("← are you a man or a woman?").show(); ele.removeClass("normal").addClass ("wrong"); ) else ( genderInfo..removeClass("error").addClass("correct").html("√").show(); ele.removeClass("wrong").addClass("normal "); ) )

    On line 14 we check how many radio selectors are selected. If 0, then the user did not select anything, we display an error message.

    And as always, we attach a gender method for the radio buttons:

    $("input").change(jVal.gender);

    Validation checkers - vehicle ownership

    Now let's copy the gender method and rename it vehicle, making the following changes:

    • Replace all genderInfo with vehicleInfo
    • Instead of #woman, enter #ship for ele.
    • In the vehicleInfo.css() expression, the value of left should be left: pos.left+ele.width()+40
    • Our if() statement should now be:
    if($("input:checked").length




    

    2024 gtavrl.ru.