Simple form validation without JS. We are writing a script for validating custom forms using jQuery. Applying validation rules based on class membership

  • ASP,
  • JavaScript
  • There are many articles on how to write your own rules for the jQuery validate plugin, but few of them explain internal work this plugin, which is what we will discuss in this article.
    This is the first part of the series "Understanding Asp.NET MVC Unobtrusive Validation"

    1. Working the jQuery validate plugin from the inside

    What we learn from this article:
    1. How to validate the form.
    2. Validation messages and how they work.
    3. Adding your own validation rules.
    4. What exactly happens when we call the validation method.

    How to validate a form
    There are 2 main ways to validate a form.1. Use class names as rules How it works

    We add to the field that needs to be validated, html attribute"class" and this will enable validation.
    So, if we want the text field to be required, we add a class = "required" attribute value to the input element.

    HTML


    JavaScript
    $(document).ready(function() ( $("form").validate(); ));
    This way you can add multiple rules to certain classes.

    Pros and cons of this approach:
    Works only with rules that do not accept arguments.
    We are using the html "class" attribute for something it is not intended for.
    But it's easy to install.

    Using the method "addClassRules"
    Using the "addClassRules" function gives us the ability to use a compound rule for a single class.

    JavaScript
    $.validator.addClassRules(( name: ( required: true, minlength: 2 ), zip: ( required: true, digits: true, minlength: 5, maxlength: 5 ) ));
    This code adds 2 new rules for the class "name" and "zip", and if we have an "input" element whose class is "zip", then the rules apply to it: its value is required, the user can only enter numbers and the length must be exactly 5 characters.

    HTML

    Information: To use own message for a specific "requires" rule in a compound rule, we need to come up with an alias for the "required" rule, create a new rule with that alias and set a default message for it.

    JavaScript
    $.validator.addMethod("newrequired", $.validator.methods.required, "new name is required");
    Or we can use the html "title" attribute, its value will be the error message for the compound rule.

    Note: Validation by class name only works for validation rules that do not take any arguments.

    2. Adding rules as a JSON object to the validate() method By the name, you should have guessed that this validation method accepts a json object, so we can define the fields that we need to validate and the validation rules for them.

    HTML

    JavaScript
    $("form").validate(( rules: ( userEmail: ( email: true, required: true ) ) ));
    Note: When we pass the "rules" object to the "validate" function, the key must be the value of the "name" attribute, not the value of the "id". As you can see in the example: the key is “userEmail”, the value of the attribute is “name”, and the attribute “id” has a different value.

    Pros and cons of this approach:

    This approach gives us the ability to use more validation rules that take arguments such as minlength, remote, equalTo, etc.
    Excellent and manually configurable control over everything.
    But the user must do separate function"validate" with different options for each form.

    Adding or removing dynamic rules.Adding rules To add a rule we must use the "rules" method to jQuery elements after the form is validated and pass the string “add” as the first parameter and as the second parameter the object of the rules that we want to add to this element (we can also pass the “message” object for the rules that we have added).

    JavaScript
    $(".input").rules("add", ( required: true, messages: ( required: true ) ))

    Removing Rules If we want to remove a rule or set of rules, we pass the string “remove” as the first parameter to the “rules” method and the second parameter will be a string that contains the rules we want to remove, separated by a space.

    JavaScript
    $(".input").rules("remove", "min max");

    Manual configuration approach JavaScript
    var validator = $("form").data("validator"); validator.settings.rules.objectName = ( required: true )
    This approach is very useful if you have rules and message objects created, you can extend the validator rules with your own:

    JavaScript
    $.extend(validator.settings, ( rules: rules, messages: messages ));

    Validation messages and how they work There are three ways to configure a validation message

    1. Pass the “messages” object to the “validate” method. The "messages" object consists of key\value pairs. The key is the value of the element's "name" attribute. The value is an object containing each rule and its message.

    JavaScript
    $("form").validate(( rules: ( userEmail: ( email: true, required: true ) ), messages: ( userEmail: ( email: "Please enter your email", required: "*" ) ) )) ;
    2. Determine the value of the element’s “title” attribute

    HTML

    3. Use default message. When a validation rule is defined, there are built-in default messages for built-in rules.

    Note: These three methods override each other based on priority, the highest priority being the passed "messages" object and the least priority being the default message.

    Adding Custom Validation Rules When we want to add more validation rules than those defined by default, we use the method
    $.validator.addMethod

    This method takes the following as parameters:

    • rule name;
    • a function that performs validation;
    • default message.
    The function that performs the validation can have two or three parameters

    JavaScript
    function validationMethod (value, element) // OR function validationMethod (value, element, params)
    Let me explain these parameters.
    Value: the value of the DOM element that will be validated
    Element: the DOM element itself
    Parameters: what we pass as a value. For this example, the validation rules are what params should equal.

    JavaScript
    $("form").validate(( rules: ( firstname: ( compare: ( type: "notequal", otherprop: "lastname" ) ) ) ));
    in this example params will be equal to (type: "notequal", otherprop: "lastname")

    Example of adding your own rule:

    JavaScript
    $.validator.addMethod("notnumbers", function(value, element) ( return !/*/.test(value); ), "Please don"t insert numbers.")

    What exactly happens when we call the "validate" method

    When we call the validate method on a form, a lot of different things happen behind the scenes:

    A "validator" object is created with all the rules and options attached to the form.
    The "validate" method attaches the "validator" using "$.data". We can get it by selecting the form and calling the jQuery function "$.data" and passing it to the "validator". The "vaidator" object is all the metadata for validation, which gives us the ability to access validation options at any time life cycle pages.
    Using this object, we can change at runtime the options we passed to the validation method, such as adding or removing rules, changing the behavior if a field is valid or invalid, or even introducing an ignore selector.

    JavaScript
    //getting the validator var validator = $("selector").data("validator")
    Note: When you call the "validate" method on a form that is already validated, it will return only the "validator" object, $.data is also used, and all previous options passed by the "validate" method will be erased.

    JavaScript
    var validator = $(".selector").validate(/* rules will be omitted */)

    Attaching Form Events
    What will happen when we click submit and the form will be entered incorrect value for the field to which we attached the validation. If one of the fields is invalid, then the validation plugin will look at it more closely to check whether it is valid or not based on events on this field.
    The form events that the plugin subscribes to are “click”, “focusin”, “focusout”, “keyup”, “submit”.
    Note: You can disable validation for certain events by passing them as keys in the validate method, and false as values.

    JavaScript
    $(".selector").validate(( onfocusout: false, onkeyup: false, onclick: false, onsubmit: false ));

    Translation of Nadeem Khedr's article "How the jQuery validate plugin works internally."

    This is a very unpleasant topic for any programmer. The more fields in the form, the larger and more complex the validation script jquery forms. There were times when programmers did validation in PHP. Such validation looked rather cumbersome. The disadvantage of this PHP validation is that you always need to use sessions or cookies. In this case, the page is constantly reloaded, which makes unnecessary requests to the database.

    Validation in jquery is much easier to do. There are several jquery plugins to validate form fields. I'll show you a very simple way. You can modify it and add your own branded checks. Figuratively speaking, errors will be placed in one array. This array will then turn into a solid string. You will see several errors in the output at once.

    Paste the following code into html document. Please note that you have one button and 3 fields.

    form ( margin:10px; border: 1px solid gray; ) input ( margin:5px; border: 1px solid gray; )


    // validation form jquery $("input").click(function ()( // collect data into one array var title = $("input").val().trim(); var text = $("input ").val().trim(); var cat = $("input").val().trim(); //process the data var error_arr = ; if(title.length == 0) error_arr.push( "description"); if(text.length == 0) error_arr.push("text"); if(cat.length == 0) error_arr.push("category"); // check for errors if(error_arr) .length > 0)( alert("You have not filled in following fields:\n" + error_arr.join(", ")); // blocking transition to another page return false; )else( console.log("No errors!"); ) ));

    Let's look at the form validation script itself. First, the data is collected into variables. Be sure to clear the data from spaces. " " is also a symbol. Next, the data is checked for the presence of characters. You can add your own branded checks. You can even use regular expressions. It all depends on the task at hand. Then there is a final check for errors. If there is at least one error, the alert will display an error. Pay attention to join(). This function collects all the elements of an array and outputs them as a delimited string. Read about arrays on the page Arrays in javascript. I don't use loops or the each() function. It's easier)). If there are no errors, then the script will move you to new page and the data will be sent. In case of a validation error, there will be no transition to another page. You will see a warning and a display of all errors (You have not filled in the following fields: description, text, category).

    From the author: When you collect information from users using a form, using at least some kind of data validation is a must. If you don't pay attention to this moment, this can lead to the loss of customers, corruption of data in the database (DB), and even the appearance of security holes in your website. Historically, form validation has always been a headache. This is easier to do on the server side thanks to full-fledged frameworks that will do everything for you, but on the client side it most often ends up using JavaScript libraries that take a lot of effort to integrate.

    Fortunately, HTML5 provides several features that can solve most of your form validation issues. Forms in HTML5 now have built-in support for validation through the use of special attributes and new input element types. This also gives you more control over your form styling via CSS.

    Take a look at the form validation example online and read on for a quick cheat sheet on the basics of form validation in HTML5.

    Special types Input element

    HTML5 introduces several new input element types. They can be used to create input fields that will only accept certain type data. Here are the new types that appeared in HTML5:

    To use one of the new types, specify its name as the value of the type attribute:

    < input type = "email" / >

    If the browser does not support this type input element, then the current element will behave like a regular text input field. It may also be helpful for you to know that some field types (such as “email” and “tel”) result in an open mobile devices special keyboards With limited set keys rather than the full QWERTY layout. More detailed information You can find information about all types of input element on the MDN website -.

    Required fields

    Simply adding a "required" attribute to an input, select, or textarea element will tell the browser that it has of this field there must be a meaning. Think of it like the red asterisk* we see on most registration forms.

    < input type = "checkbox" name = "terms" required >

    The problem here is that almost any information will satisfy this requirement, i.e., for example, you can pass validation by simply putting a space (we'll show you how to avoid this).

    When you specify the required attribute on fields like email or url, the browser expects there to be a certain pattern against which it can validate the information, but this validation is very lenient and misses e-mail addresses like “z@zz” (read on to find out how to deal with this).

    Limits

    We can install basic restrictions, such as maximum length or minimum and maximum values ​​for numeric fields. To limit the length of input or textarea elements, use the "maxlength" attribute. This is done so that it is generally impossible to enter a string longer than the value of the “maxlength” attribute. If you try to insert a line that exceeds the limit, the form will simply cut it off.

    Decor

    CSS3 pseudo-classes allow us to style any form field depending on its state. Here are the pseudo-classes:

    It means that required fields Yours may look one way, optional ones may look different, etc. In our demo, we combined the "valid" and "invalid" selectors with the "focus" pseudo-class to color the form fields red and green colors, when the user selects them and starts typing something into them.

    input:focus:invalid, textarea:focus:invalid( border:solid 2px #F5192F; ) input:focus:valid, textarea:focus:valid( border:solid 2px #18E109; background-color:#fff; )

    input: focus: invalid,

    textarea : focus : invalid (

    border : solid 2px #F5192F;

    input: focus: valid,

    textarea : focus : valid (

    border : solid 2px #18E109;

    background - color : #fff;

    Tooltips

    You've probably noticed that when you try to submit an incorrectly filled out form, tooltips appear. By setting the "title" attribute to our fields, we can add additional hints about what values ​​our validation rules expect the user to provide.

    Please note that different browsers display tooltips differently. IN Chrome browser meaning title attribute will appear below the main text of the error message and will have smaller size font than the error text. Firefox browser will not display your text for the tooltip at all unless you use the "pattern" attribute, which will be used for the pattern information.

    An example of what we can achieve can be seen in the example below. The example also includes validation for correct email entry. Below I will show two options for scripts with and without email validation.

    As you can see, until all the fields are filled in, the script will not allow you to submit the form, and the correct address must be entered in the e-mail field. First, I'll show you how to do it simple check to fill in the fields without email checks. What if your form does not have this field and you need to check just the text field so that it is not empty and empty notifications do not come to your email.

    To implement our plan, we first need to create the form itself. You may already have it, but if you want to introduce this material into it, you will need to adapt it to your shape. I will show everything using my own example. My form will not send anything, this article does not have a handler for sending letters, so as not to complicate the material. The email sending handler is another story. First, the HTML code of the form itself.

    You can see from the code that our form consists of three fields - name, email and test field. There are a few more important points, which will be needed in any case for proper operation script. Let's take it in order.

    • id="file_form" - ID for our form. ID is required, it will also be used in the script.
    • - required block. This is a container for displaying error messages from the script. this block can be placed outside the form. Give him any styles. In the example, this is the red text that indicates an empty field.
    • onclick="frmotpr();" - an event that will launch a function from our script when the button is clicked. This event has been added to the SEND button. The penultimate line in the code.
    • All fields are also assigned IDs and classes. They will also be needed for our validation script. The ID for the e-mail field is especially important for our future script, which will check the correctness of the entered e-mail.

    Now to make it normal appearance to our form, let's add some CSS styles. If you use them on your site, then add them to your styles file.

    #file_form( width:300px; background:#fff; padding:15px; margin:3px; -webkit-border-radius:25px; -moz-border-radius:25px; border-radius:25px; box-shadow:0 0 10px rgba(0,0,0,.1); border:1px solid #36c; .in_pl( width:90%; margin-bottom:15px; padding:10px 15px; border-radius:25px; border:none; box-shadow:0 0 5px rgba(0,0,0,.2) inset; background:#fff; ) .in_pl:focus( background:#fff; ) #sub_f( padding:5px 15px; border:none; border -radius:25px; box-shadow:0 0 2px 1px rgba(0,0,0,.2); background:#36c; cursor:pointer; ) .fl_fr( width:100%; text-align:center; font-size:15px; color:#333; cursor: pointer; border:none; margin-bottom:10px; ) #messenger( text-align:center; display:none; color:#f00; margin:15px 0; .notvalid(background:rgba(255,0,0,.2);)

    These styles set parameters for the form itself, fields, and buttons. I won’t describe all the lines and what each one does, there are CSS tutorials for that. I will list only the two most important ones.

    • #messenger are styles for the same block with message output. Main parameter for this class it is display:none. That is, we initially hide the block.
    • .notvalid are styles for the class that will be assigned by our script to the field that is not filled in or filled in incorrectly. I will mention this class again below.

    Now that we have finished form or you configured your form according to my instructions, added IDs to it, mine or yours, required block and the button event, we can start connecting the script.

    Since our script works with using jQuery, it needs to be connected jQuery library. If it is not connected previously, do so by adding this line:

    You can read where and how to add the library correctly in the article -.

    After the library, not before it, but after it, we need to connect our long-awaited form validation script. as I wrote earlier, the first option would be to first check the field for completion, without checking the correctness of the entered email. The script itself has next view: