Jquery validate error list

The ultimate goal of this plugin is to make working with forms more fun for everyone. By improving the interaction, it is easier and less annoying for the user to fill out the form and submit it.

link Goals

The ultimate goal of this plugin is to make working with forms more fun for everyone. By improving the interaction, it is easier and less annoying for the user to fill out the form and submit it.

To achieve this, it is important that the plugin is actually deployed on websites around the world, so a lot of focus is spent on making it easy for developers – that’s you – to use the plugin.

The plugin can never replace server-side validation and doesn’t intend to do so. Having both in place gives you the necessary security for your application, as well as improved usability.

link Markup recommendations

Mandated: A ‘name’ attribute is required for all input elements needing validation, and the plugin will not work without this. A ‘name’ attribute must also be unique to the form, as this is how the plugin keeps track of all input elements. However, each group of radio or checkbox elements will share the same ‘name’ since the value of this grouping represents a single piece of the form data.

Optionally: Each input can have a label associated with it, where the ‘for’ attribute of the label refers to the ‘id’ attribute of the input. It’s also a common practice to have ‘id’ and ‘name’ attributes with the same value, although keep in mind that since this plugin does not use the ‘id’ attribute, this is not mandatory.

1

2

<label for="firstname">Firstname</label>

<input id="firstname" name="fname">

link Methods

A validation method implements the logic to validate any element. Provided are a set of default validation methods, such as required. Apart from required itself and equalTo, all validation methods declare an element valid when it has no value at all. That way an email field is optional unless required is specified. You can specify an element input to contain a valid email address, or nothing at all. Use jQuery.validator.addMethod to implement custom methods.

link Rules

A validation rule applies one or more validation methods to an input element. You can specify validation rules via metadata or via plugin settings (option rules). The decision is often influenced by serverside infrastructure. If a web framework is used, it is often easier to use metadata, which is also good for fast prototyping. Plugin settings produce cleaner markup, though valid markup results from both.

link Fields with complex names (brackets, dots)

If your form consists of fields using names that aren’t legal JavaScript identifiers, you have to quote those names when using the rules option:

1

2

3

4

5

6

7

8

9

10

// dots need quoting, too!

"user.address.street": "required"

link Refactoring rules

Whenever you have multiple fields with the same rules and messages, refactoring those can reduce a lot of duplication. Using addMethod() and addClassRules() are most effective for that.

Let’s consider an example where you have ten customer fields, each required and with a minlength of 2. You need custom messages for both rules. To avoid having to specify those rules and messages again and again, we can alias existing methods with different messages and group them into a single class:

1

2

3

4

5

6

7

8

9

// alias required to cRequired with new message

$.validator.addMethod("cRequired", $.validator.methods.required,

"Customer name required");

$.validator.addMethod("cMinlength", $.validator.methods.minlength,

// leverage parameter replacement for minlength, {0} gets replaced with 2

$.validator.format("Customer name must have at least {0} characters"));

// combine them both, including the parameter for minlength

$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });

With that in place, we can add a class customer to all customer fields and be done with it:

1

2

3

<input name="customer1" class="customer">

<input name="customer2" class="customer">

<input name="customer3" class="customer">

You can also reuse existing methods inside other custom methods, to reuse certain implementations. For example, if you’re writing a custom method for validating email addresses inside a single field, you could call the existing email method for each email:

1

jQuery.validator.methods.email.call(this, email, element)

link Error messages

An error message displays a hint for the user about invalid elements, and what is wrong. There are four ways to provide error messages. Via the title attribute of the input element to validate, via data attributes, via error labels and via plugin settings (option messages).

All validation rules included here provide a default error message which you can use for prototyping, because it is used when no specific message is provided.

The priorities are as follows: A custom message (passed by plugin options), the element’s title, the default message.

When using data attributes, you can set a generic message for all rules, or specific messages per rule:

1

2

<input required data-msg="Please fill this field">

<input data-rule-minlength="2" data-rule-maxlength="4" data-msg-minlength="At least two chars" data-msg-maxlength="At most four chars">

link Error message display

Error messages are handled via label elements with an additional class (option errorClass). The link between the message and the invalid element is provided via the labels for attribute. When provided in the markup, they are shown and hidden accordingly, and otherwise created on demand. By default, labels are created after the invalid element, this is also customizable (option errorPlacement). It is also possible to put them into an error container (option errorLabelContainer). To use a different element then a label, specify the errorElement option.

link General messages

In addition to field-specific messages you can display a general «your form is invalid, please fix the highlighted fields!» message in a container anywhere on your page, eg. above the form (option errorContainer). The container is shown and hidden when errors occur and are fixed accordingly. The container for error labels (option errorLabelContainer) can also be nested inside the error container.

link Focusing of invalid elements

By default, the first invalid element in a form is focused after submitting a form with invalid elements. To prevent confusion on the behalf of the user, the plugin remembers the element that had focus when the form was submitted, and refocuses that element. That way the user can try to fill out elements of the form at the end, without being forced to focus them again and again. This can be disabled (option focusInvalid).

link Form submit

By default, the form submission is prevented when the form is invalid, and submitted as normal when it is valid. You can also handle the submission manually (option submitHandler).

link Skipping validation on submit

To skip validation while still using a submit-button, add the attribute «formnovalidate» to that input:

1

2

<input type="submit" name="go" value="Submit">

<input type="submit" formnovalidate name="cancel" value="Cancel">

This used to work by adding class="cancel" to the input, this is now deprecated.

Demo for the cancel button

link Validation event

By default, forms are validated on submit, triggered by the user clicking the submit button or pressing enter when a form input is focused (option onsubmit). In addition, once a field was highlighted as being invalid, it is validated whenever the user types something in the field (option onkeyup). When the user enters something invalid into a valid field, it is also validated when the field loses focus (option onfocusout).

The goal of these interactions is to provide feedback as early as possible, whilst avoiding user annoyance. Displaying error messages before the user had the chance to even type something is not helpful.

link Developing and debugging a form

While developing and debugging the form, you should set the debug option to true. That prevents form submission on both valid and invalid forms and outputs some helpful messages to window.console (available via Firebug or Firebug Lite) that help debugging. When you have everything set up and don’t get any error messages displayed, check if your rules all accept empty elements as valid (like email or url methods).

Some issues are caused by certain form element’s names. A name you should avoid is «submit» (for submit buttons and anything else). Browsers expose form elements as properties of the form element, by their name, in this case hiding native methods like submit(). Just don’t use name=»submit» and you’re good.

link Validating multiple forms on one page

The plugin can handle only one form per call. In case you have multiple forms on a single page which you want to validate, you have to initialise them all individually:

1

2

3

$( "form" ).each( function() {

$( this ).validate( options );

You can avoid having to duplicate the plugin settings by modifying the defaults, using jQuery.validator.setDefaults to override multiple settings at once.

There has been a lot of talk on our blog recently regarding forms. We have looked at rules for displaying error messages, creating accessible forms and would you have guessed, I’m now going to talk about implementing accessible form errors! Well, it makes a change from all of those HTML5 and CSS3 posts that are flooding my daily feeds of late.
A screenshot of the demo form page with error messages.

Anyway, this short post looks at how we can begin to deliver a better experience for our users when it comes to displaying form errors. As jQuery is my preferred library of choice and the Validation plug-in provides an excellent starting point, we will use them both to form the basis of this article. Out of the box the jQuery Validation plug-in provides some reasonable defaults, however because of the vast options available in the plug-in, a developer can use it for great good or great evil. Following these tips, we are able to improve the accessibility of the plugins out-of-the-box defaults, which ultimately provides a better experience for our users. I will start by making a few assumptions at this point:

  1. You have read Three rules for creating accessible forms and understand how to create accessible forms;
  2. You have a server-side validation method. It ensures there is a fallback for that minority who do not have JavaScript available, and stops hackers who can turn off JavaScript to avoid validation;
  3. You have downloaded the relevant jQuery and jQuery Validation plug-in files.

A simple form

First we need our form mark-up to be clean and tidy. Something like this perhaps:

<form action="#" id="formDemo">
    <fieldset>
      <legend>Your Details></legend>
        <div>
            <label for="f0">First Name</label> <input class="required" id="f0" name="f0" type="text" />
        </div>
        <div>
            <label for="f1">Last Name</label> <input class="required" id="f1" name="f1" type="text" />
        </div>
        <div>
            <label for="f2">Telephone Number</label> <input class="required" id="f2" name="f2" type="text" />
        </div>
        <div>
            <label for="f3">Email Address</label> <input class="required" id="f3" name="f3" type="text" />
        </div>
    </fieldset>
    <div>
        <input type="submit" value="Submit" />
    </div>
</form>

Setup the jQuery validation function

Our next step is to call the jQuery Validation function. There are several ways you can do this, but for the sake of this article I want to keep it clean and simple. Thus I will call the jQuery Validation plug-in from within my own function (accValidate):

$(document).ready(function() {
    /*Initialise the validation function */
    $('#formDemo').accValidate();
});
jQuery.fn.accValidate = function(){
var form = this;

//The jQuery validation plug-in in action
$(form).validate({

//Optional, but for demo purpose we only want to validate on submitting the form
onfocusout: false,
onkeyup: false,
onclick: false,

//We are going to focus on the first link in the error list so i have disabled
//the input error focus option in jQuery Validation

focusInvalid: false,

The excellent jQuery Validation plug-in allows us to configure how and when the validation script is run. For the purpose of our demo, we will disable the onfocus, onkeyup and onclick validation options. We only want it to validate on submission of the form. Next the plug-in allows us to define the element to use for the error messages and their location:

    …
    //Set the element which will wraps the inline error messages
errorElement: "strong",
//Location for the inline error messages
//In this case we will place them in the associated label element
errorPlacement: function(error, element) {
error.appendTo($('label[for=&quot;' + $(element).attr('id') + '&quot;]', form));
},
&hellip;</pre>

We will display a simple inline error message for each input as part of the associated label. Why here you ask? Well it will depend on the situation and the input type in question (there are always some exceptions), but in this case it works well for screen readers that typically read out the associated label text (and therefore the error message) when the input field receives focus.

Creating the error summary

So far our jQuery Validation plug-in has done an excellent job! But now we are going to head off the beaten track slightly and create the error summary with the help of some of the functionality available within the plug-in:

    …
    //Create our error summary that will appear before the form
    showErrors: function(errorMap, errorList) {
    if (submitted && errorList) {
    var $errorFormId = 'errors-' + form.attr('id')

    //Reset and remove error messages if the form
    //has been validated once already
    summary = &quot;&quot;;
    $('label .error', form).remove();

    //Create our container if one doesnt already exits
    //better than an empty div being in the HTML source
    if($('#' + $errorFormId).length == 0) {
        $('&lt;div id=&quot;' + $errorFormId + '&quot;/&gt;').insertBefore(form);
    }

    //Generate our error summary list
    for (error in errorList) {
        //get associated label text to be used for the error summary
        var $errorLabel = $('label[for=&quot;' + $(errorList[error].element).attr('id') + '&quot;]').text();
        summary += '&lt;li&gt;&lt;a href=&quot;#' + errorList[error].element.id + '&quot;&gt;' + $errorLabel + ': ' + errorList[error].message + '&lt;/a&gt;&lt;/li&gt;';
        }

        //Output our error summary and place it in the error container
        $('#' + $errorFormId).html('&lt;h2&gt;Errors found in the form&lt;/h2&gt;&lt;p&gt;&lt;em&gt;Whoops!&lt;/em&gt; - There is a problem with the form, please check and correct the following:&lt;/p&gt;&lt;ul&gt;' + summary + '&lt;/ul&gt;');

        //Focus on first error link in the error container
        //Alternatively, you might want to use the Validation default option (focusInvalid)
        $('#' + $errorFormId + ' a:eq(0)').focus();

        //Move the focus to the associated input when error message link is triggered
        //a simple href anchor link doesnt seem to place focus inside the input
        $('#' + $errorFormId + ' a').click(function() {
        $($(this).attr('href')).focus();
        return false;
    });
}
this.defaultShowErrors();
submitted = false;
},
invalidHandler: function(form, validator){
    submitted = true;
}
&hellip;</pre>

This creates our error summary, based on the errors found in the form, and inserts it before the form being validated. It clearly lists all errors and, as an added bit of functionality, provides anchor links allowing the user to easily skip to input fields that have an error. You might also notice that we place the focus on the first link in the error summary when the form is submitted. This approach has undergone a fair amount of discussion and testing, the result of which lead us to believe that this approach worked well for users addressing errors in the form. There we have it. You can checkout the demo here to see the form validation in action. The jQuery Validation plug-in offers many useful features, for example we haven’t even looked at custom error messages or checkbox validation. But this should give you an idea of how we can start to deliver accessible error messages using a plug-in like jQuery Validation. Have a different plug-in or library of choice for validating forms? Why not share it here...

jQuery Validation Plugin — Form validation made easy

release
Build Status
devDependency Status
jsDelivr Hits

The jQuery Validation Plugin provides drop-in validation for your existing forms, while making all kinds of customizations to fit your application really easy.

Getting Started

Downloading the prebuilt files

Prebuilt files can be downloaded from https://jqueryvalidation.org/

Downloading the latest changes

The unreleased development files can be obtained by:

  1. Downloading or Forking this repository
  2. Setup the build
  3. Run grunt to create the built files in the «dist» directory

Including it on your page

Include jQuery and the plugin on a page. Then select a form to validate and call the validate method.

<form>
	<input required>
</form>
<script src="jquery.js"></script>
<script src="jquery.validate.js"></script>
<script>
    $("form").validate();
</script>

Alternatively include jQuery and the plugin via requirejs in your module.

define(["jquery", "jquery.validate"], function( $ ) {
	$("form").validate();
});

For more information on how to setup a rules and customizations, check the documentation.

Reporting issues and contributing code

See the Contributing Guidelines for details.

IMPORTANT NOTE ABOUT EMAIL VALIDATION. As of version 1.12.0 this plugin is using the same regular expression that the HTML5 specification suggests for browsers to use. We will follow their lead and use the same check. If you think the specification is wrong, please report the issue to them. If you have different requirements, consider using a custom method.
In case you need to adjust the built-in validation regular expression patterns, please follow the documentation.

IMPORTANT NOTE ABOUT REQUIRED METHOD. As of version 1.14.0 this plugin stops trimming white spaces from the value of the attached element. If you want to achieve the same result, you can use the normalizer that can be used to transform the value of an element before validation. This feature was available since v1.15.0. In other words, you can do something like this:

$("#myForm").validate({
	rules: {
		username: {
			required: true,
			// Using the normalizer to trim the value of the element
			// before validating it.
			//
			// The value of `this` inside the `normalizer` is the corresponding
			// DOMElement. In this example, `this` references the `username` element.
			normalizer: function(value) {
				return $.trim(value);
			}
		}
	}
});

Accessibility

For an invalid field, the default output for the jQuery Validation Plugin is an error message in a <label> element. This results in two <label> elements pointing to a single input field using the for attribute. While this is valid HTML, it has inconsistent support across screen readers.

For greater screen reader support in your form’s validation, use the errorElement parameter in the validate() method. This option outputs the error in an element of your choice and automatically adds ARIA attributes to the HTML that help with screen reader support.

aria-describedby is added to the input field and it is programmatically tied to the error element chosen in the errorElement parameter.

$("#myform").validate({
  errorElement: "span"
});
<label for="name">Name</label>
<input id="name" aria-describedby="unique-id-here">
<span class="error" id="unique-id-here">This field is required</span>

Learn more about errorElement

License

Copyright © Jörn Zaefferer
Licensed under the MIT license.

Есть множество статей о том, как написать свои правила для плагина jQuery validate, но мало какие из них объясняют внутреннюю работу этого плагина, что мы и обсудим в этой статье.
Это первая часть серии статей «Понимание ненавязчивой валидации Asp.NET MVC»

1. Работа плагина jQuery validate изнутри
2. Понимание Html-кода, сгенерированного ненавязчивой валидацией в ASP.Net MVC
3. Внутренняя работа плагина unobtrusive jQuery validate в ASP.Net MVC.

Что мы узнаем из этой статьи:
1. Как валидировать форму.
2. Сообщения валидации и как они работают.
3. Добавление собственных правил валидации.
4. Что именно происходит, когда мы вызываем метод валидации.

Как валидировать форму

Есть 2 основных способа, чтобы валидировать форму.

1. Использовать имена классов как правила

Как это работает

Мы добавляем к полю, которое нужно провалидировать, html атрибут «class», и это подключит валидацию.
Итак, если нам нужно, чтобы текстовое поле было обязательным мы добавляем в элемент input значение атрибута class = «required»

Html

<form action="/" method="post">
  <input id="Name" type="text" name="Name" value="" class ="required"  />
  <input type="submit" value="Submit" />
</form>

JavaScript

$(document).ready(function() {
  $('form').validate();
});

Так вы можете добавить к определенным классам несколько правил.

Плюсы и минусы такого подхода:
Работает только с правилами, которые не принимают аргументов.
Мы используем html атрибут «class» для того, для чего он не предназначен.
Но его легко установить.

Использование метода «addClassRules»

Использование функции «addClassRules» дает нам возможность использовать составное правило для одного класса.

JavaScript

 $.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});

Этот код добавляет 2 новых правила для класса «name» и «zip», и, если у нас есть элемент «input», у которого класс «zip», то к нему применяются правила: его значение является обязательным, пользователь может вводить только цифры и длина должна быть точно 5 символов.

Html

<input class="zip" type="text" name="zipCode" />

Информация: Чтобы использовать собственное сообщение для определенного правила requires в составном правиле, нам нужно придумать псевдоним для правила «required», создать новое правило с этим псевдонимом и установить для него сообщение по умолчанию.

JavaScript

$.validator.addMethod("newrequired", $.validator.methods.required, "new name is required");

Или мы можем использовать html атрибут «title», его значение будет сообщением об ошибке для составного правила.

Заметка: Валидация по имени класса работает только для правил валидации, не принимающих никаких аргументов.

2. Добавление правил как JSON объекта к методу validate()

По названию, вы должны были догадаться, что этот метод валидации принимает объект json, поэтому мы можем определить поля, которые нам нужно валидировать и правила валидации для них.

Html

<form>
  <input id="something" type="text" name="userEmail" />
  <input id="submit" type="submit" value="submit" />
</form>

JavaScript

$('form').validate({
  rules: {
    userEmail: {
      email: true,
      required: true
    }
  }
});

Заметка: Когда мы передаем объект «rules» функции «validate» ключом должно быть значение атрибута «name», а не значение «id». Как можно увидеть в примере: ключ -это «userEmail», значение атрибута «name», а у атрибута «id» другое значение.

Плюсы и минусы этого подхода:

Этот подход дает нам возможность использовать больше правил валидации, которые принимают аргументы, такие как minlength, remote, equalTo и т.д.
Отличный и настраиваемый вручную контроль над всем.
Но пользователь должен делать отдельную функцию «validate» с разными опциями для каждой формы.

Добавление или удаление динамических правил.

Добавление правил

Чтобы добавить правило мы должны использовать метод «rules» для элементов jQuery после того как форма провалидирована и передавать как первый параметр строку «add» и как второй параметр — объект правил, которые мы хотим добавить к этому элементу (также мы можем передавать объект «сообщение» для правил, которые мы добавили).

JavaScript

$('.input').rules('add', {
  required: true,
  messages: {
    required: true
  }
})

Удаление правил

Если мы хотим удалить правило или набор правил, мы передаем строку «remove», как первый параметр для метода «rules», а вторым параметром будет строка, которая содержит правила, которые мы хотим удалить, отделенные пробелом.

JavaScript

$('.input').rules('remove', 'min max');
Подход настройки вручную

JavaScript

var validator = $('form').data('validator'); 
validator.settings.rules.objectName = {
  required: true
}

Этот подход очень полезен, если у вас есть созданные правила и объекты сообщений, вы можете расширить правила валидатора своими собственными:

JavaScript

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

Сообщения валидации и как они работают

Есть три способа настроить сообщение валидации

1. Передать объект «messages» методу «validate». Объект «messages» состоит из пар ключзначение. Ключ — это значение атрибута «name» элемента. Значение — объект, содержащий каждое правило и его сообщение.

JavaScript

$('form').validate({
  rules: {
    userEmail: {
    email: true,
    required: true
    }
  },
  messages: {
    userEmail: {
    email: "Please enter your email",
    required: "*"
    }
  }
});

2. Определить значение атрибута «title» элемента

Html

<input id="Email" title="you have to enter a value" type="text" name="Email" />

3. Использовать сообщение по умолчанию. Когда определяется правило валидации, есть встроенные сообщения по умолчанию для встроенных правил.

Заметка: Эти три способа переопределяют друг друга, основываясь на приоритетности, самый приоритетный — переданный объект «messages», а наименее приоритетный — сообщение по умолчанию.

Добавление собственных правил валидации

Когда мы хотим добавить больше правил валидации, чем определены по умолчанию, мы используем метод
$.validator.addMethod

Этот метод принимает как параметры следующее:

  • имя правила;
  • функцию, которая осуществляет валидацию;
  • сообщение по умолчанию.

Функция, которая производит валидацию, может быть с двумя или тремя параметрами

JavaScript

 function validationMethod (value, element)
// OR
function validationMethod (value, element, params)

Давайте объясню эти параметры.
Значение: значение DOM элемента, который будет валидироваться
Элемент: сам элемент DOM
Параметры: то, что мы передаем как значение. Для этого примера правила валидации — это то, чему должен равняться params.

JavaScript

$('form').validate({
  rules: {
    firstname: {
      compare: {
        type: "notequal",
        otherprop: "lastname"
      }
    }
  }
});  

в этом примере params будет равен {type:«notequal», otherprop: «lastname»}

Пример добавления собственного правила:

JavaScript

$.validator.addMethod("notnumbers", function(value, element) {
  return !/[0-9]*/.test(value);
},
"Please don't insert numbers.")

Что именно происходит, когда мы вызываем метод «validate»

Когда мы вызваем метод validate на форме, за кулисами происходит много разных вещей:

Создается объект «validator» со всеми правилами и опциями, присоединенными к форме.
Метод «validate» присоединяет «validator» используя «$.data». Мы можем получить его выбрав форму и вызвав функцию jQuery «$.data» и передать ее «validator». Объект «vaidator» — это все метаданные для валидации, которые дают нам возможность доступа к опциям валидации в любое время жизненного цикла страницы.
Используя этот объект, мы можем изменить во время выполнения опции, которые мы передали методу валидации, такие как добавление или удаление правил, изменение поведения, если поле валидное или невалидное, или даже введение селектора игнорирования.

JavaScript

 //getting the validator
var validator = $("selector").data("validator")

Заметка: Когда вы вызываете метод «validate» на форме, которая уже провалидирована, он вернет только объект «validator», используется также $.data, и все предыдущие опции, переданные методом «validate», будут стерты.

JavaScript

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

Присоединение событий формы

Что произойдет, когда мы нажмем submit(отправить форму), и в форме будет введено неверное значение для поля, к которому мы присоединили валидацию. Если одно из полей невалидное, то плагин валидации будет присматриваться к нему более пристально, чтобы проверять, валидное оно или нет, по событиям на этом поле.
Сообытия формы, на которые подписывается плагин — это «click», «focusin», «focusout», «keyup», «submit».
Заметка: Вы можете отключить валидацию по определенным событиям, передав их как ключи в методе validate, и false в качестве значений.

JavaScript

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

Перевод статьи Nadeem Khedr «How the jQuery validate plugin works internally». nadeemkhedr.wordpress.com/2012/08/12/how-the-jquery-validate-plugin-works-internally/#goCallValidate

update 01.06.13: добавлены ссылки на другие посты серии

Из этой статьи вы узнаете, как реализовать простую валидацию формы с помощью jQuery-плагина.

Использование jQuery-плагина для проверки данных в форме удобно по нескольким причинам. Этот способ предоставляет дополнительные опции – например, возможность выводить сообщения об ошибках и добавлять обработку различных условий проверки. Применение готового плагина также позволяет добавлять валидацию в формы без внесения видимых изменений в макет страницы. Условия проверки можно с легкостью изменять, добавлять и удалять на любом этапе разработки.

  • Приступаем к работе
  • Валидация первой формы
  • Опции validate() метода
  • Добавление правил валидации для полей ввода
  • Создание собственных сообщений об ошибках
  • Кастомизация сообщений об ошибках
  • Дополнительные опции настройки плагина
  • Формы jQuery, доступные на CodeCanyon
    • Конструктор пошаговых jQuery форм Timon Step Form
    • Smart Forms
    • Just Forms Advanced
    • Forms Plus JS
    • Sky Forms
  • Заключение

В этом руководстве мы будем использовать плагин для валидации форм под названием jQuery Validation Plugin. Данный плагин имеет обширный набор функций, а также позволяет добавлять пользовательские условия проверки данных.

Перед использованием расширения на странице нам нужно будет добавить к нашему проекту необходимые файлы. Таких файлов два – первый включает в себя основную функциональность плагина для проверки базовых пользовательских данных. Второй файл содержит дополнительные методы валидации для проверки номеров банковских карт, телефонов и так далее.

Добавить файлы в проект можно с помощью менеджера пакетов – Bower или npm. Кроме того, можно получить прямую CDN-ссылку на эти файлы и вставить ее в тег script на странице. Поскольку это jQuery-плагин, вам также понадобится ссылка на соответствующую библиотеку:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

После того, как ссылки добавлены в код страницы, можно приступать к валидации любой формы с помощью метода validate.

Рассматриваемый нами плагин можно использовать без внесения каких-либо заметных изменений в разметку страницы. Единственная поправка, которую вам потребуется сделать – это добавить id или class к форме, к которой нужно подключить валидацию.

Ниже приведена разметка базовой формы, ввод данных в которой мы будем проверять с помощью jQuery-плагина.

<form id="basic-form" action="" method="post">
<p>
<label for="name">Name <span>(required, at least 3 characters)</span></label>
<input id="name" name="name" minlength="3" type="text" required>
</p>
<p>
<label for="email">E-Mail <span>(required)</span></label>
<input id="email" type="email" name="email" required>
</p>
<p>
<input class="submit" type="submit" value="SUBMIT">
</p>
</form>

Для проверки введенной информации не потребуется написание дополнительного кода на JavaScript. При этом плагин обеспечит вывод сообщений об ошибках под каждым текстовым полем. У нас также будет возможность оформить сообщения в любом желаемом стиле.

Для подключения валидации к этой форме надо всего лишь вставить приведенный ниже фрагмент, написанный на JavaScript, в код страницы:

$(document).ready(function() {
$("#basic-form").validate();
});

Подразумевается, что вы уже добавили к проекту необходимые файлы плагина. Вставка приведенного выше фрагмента кода обеспечит надлежащую проверку формы и вывод сообщений об ошибках. Вот рабочая демонстрация плагина:

Рассматриваемая нами библиотека обеспечивает максимально дружеское отношение к пользователю: сообщения об ошибках появляются только в том случае, когда это действительно необходимо. К примеру, если вы пройдетесь по полям для ввода имени и адреса электронной почты, не вводя никаких данных, сообщения об ошибке вы не получите. Однако если вы перейдете на поле для ввода email-адреса после введения всего одной буквы в поле имени, вы увидите сообщение о том, что имя должно состоять как минимум из трех символов.

Сообщения об ошибках передаются в DOM (объектную модель документа) с помощью элемента label. Поскольку этот элемент предусматривает класс error, к сообщениям можно легко применить собственные стили. То же самое справедливо в отношении invalid input, у которого тоже имеется класс error.

В предыдущем примере мы вызывали метод validate() без передачи ему каких-либо параметров. Однако у нас есть возможность передать этому методу объект, содержащий множество параметров. Значения этих параметров будут определять способы, с помощью которых плагин будет проводить валидацию данных, выводить ошибки и так далее.

Если вы хотите, чтобы плагин игнорировал какие-то элементы в ходе проверки, вы можете передать нужный класс или селектор в метод ignore(). С этого момента плагин будет игнорировать класс при проверке данных в форме.

Вы также можете передать определенные правила в метод validate() для установления правил, в соответствии с которыми должна проверяться введенная информация. Значением параметра rules должны быть пары «ключ-значение». Ключом в каждом случае является название проверяемого элемента, а значением – набор правил для проверки информации.

Также можно добавить проверку условий данных в различных полях – с использованием ключевого слова depends («зависит от») и возвращая, соответственно, результат true («истинно») или false («ложно»). Ниже приведен пример использования простого набора правил для определения корректности введенных данных:

$(document).ready(function() {
$("#basic-form").validate({
rules: {
name : {
required: true,
minlength: 3
},
age: {
required: true,
number: true,
min: 18
},
email: {
required: true,
email: true
},
weight: {
required: {
depends: function(elem) {
return $("#age").val() > 50
}
},
number: true,
min: 0
}
}
});
});

В приведенном выше фрагменте кода ключи name («имя»), age («возраст»), email и weight («вес») представляют собой названия элементов ввода input. Каждому ключу соответствует объект-значение, а пары ключей и значений определяют логику проверки информации, введенной в форму.

Такие опции валидации схожи с атрибутами, которые вы можете добавить в разметку формы. Например, установка параметра required на true сделает элемент обязательно необходимым для успешной отправки формы. Установление minlength на значение 3 обяжет пользователей вводить в поле как минимум три символа. Есть и другие встроенные методы валидации, с которыми можно ознакомиться на странице с технической документацией.

Важный момент, на который необходимо обратить внимание в приведенном выше коде – использование depends для того, чтобы сделать обязательным условием ввод веса, если возраст превышает 50 лет. Условие реализовано с помощью возвращения значения true функцией обратного вызова в том случае, если значение, введенное в поле age, превышает 50.

Рассматриваемый нами плагин позволяет создавать собственный набор сообщений об ошибках, соответствующих различным правилам проверки данных, введенных в форму. Создание сообщения об ошибке начинается с задания объекта-значения для ключа messages. Для каждого поля ввода определяется такая пара ключа и значения, и соответствующее сообщение об ошибке.

Ниже приведен пример кода, который обеспечивает вывод сообщений об ошибках при вводе неверных данных в любое из полей формы:

messages : {
name: {
minlength: "Name should be at least 3 characters"
},
age: {
required: "Please enter your age",
number: "Please enter your age as a numerical value",
min: "You must be at least 18 years old"
},
email: {
email: "The email should be in the format: abc@domain.tld"
},
weight: {
required: "People with age over 50 have to enter their weight",
number: "Please enter your weight as a numerical value"
}
}

Как и правила, messages опираются на названия полей ввода. Каждое из этих полей принимает объект, состоящий из ключа и значения. Ключом является правило валидации, а значением – сообщение об ошибке, которое выводится в случае нарушения правила.

Например, поле age с помощью свойства required вызовет сообщение об ошибке, если останется незаполненным. Кроме того, если введенная информация не является числовым значением, поле вызовет ошибку number.

Как вы сможете убедиться, плагин отображает сообщения об ошибках, используемые по умолчанию в том случае, если вы не предоставили ему свои собственные. Попробуйте ввести различные данные в приведенный ниже демонстрационный образец, и вы увидите как стандартные, так и кастомные уведомления об ошибках.

Иногда возникает необходимость добавления собственных классов к элементам ввода – для использования дополнительных правил или для лучшей интеграции с существующей темой оформления сайта.

Классы, связанные с корректными и неверными элементами ввода, можно менять с использованием ключей errorClass и validClass. Это поможет предотвратить нежелательные конфликты, которые могут возникать при повторном использовании одного и того же названия класса. По умолчанию класс ошибки errorприсваивается каждому недопустимому входному элементу и метке. Допустимый класс valid присваивается каждому корректному входному элементу.

При этом важно помнить, что присвоение errorClass уведомлениям fail-alert удаляет класс error из недопустимых элементов. Для присвоения нескольких классов одному и тому же элементу следует использовать errorClass: «error fail-alert». То же самое касается validClass.

Если пользователь вводит корректные данные, дополнительные метки к форме не добавляются. Таким образом, классы validClass остаются присвоенными корректным входным элементам.

Дополнительный JavaScript-код используется только для присвоения классов:

$(document).ready(function() {
$("#basic-form").validate({
errorClass: "error fail-alert",
validClass: "valid success-alert",
// ... More validation code from previous example
Далее приведен CSS -код, который мы будем использовать для оформления сообщений об ошибках:
label.error.fail-alert {
border: 2px solid red;
border-radius: 4px;
line-height: 1;
padding: 2px 0 6px 6px;
background: #ffe6eb;
}
input.valid.success-alert {
border: 2px solid #4CAF50;
color: green;
}

Помимо создания стиля для сообщений об ошибках, мы также добавим собственный стиль к допустимым входным элементам. Ниже приводится демонстрационный пример с готовым результатом.

Вы можете отключить валидацию при случайном переходе в поле с помощью клавиши или при клике мышью. Для этого надо установить параметры onfocusout, onkeyup, или onclick на false. Обратите внимание, что логическое true не является допустимым значением для этих событий. Другими словами, если вы хотите, чтобы плагин осуществлял валидацию при этих событиях – просто оставьте соответствующие ключи без изменений.

У вас также есть возможность изменить элемент, который используется для вывода ошибок. По умолчанию используется label, но при желании вы можете изменить его на em или любой другой элемент, используя параметр errorElemet. Выбранный элемент, в свою очередь, можно обернуть в другой HTML-элемент, применив параметр wrapper.

Рассмотренные варианты – наиболее типичные опции валидации данных. Кроме этих вариантов, вам могут пригодиться и некоторые другие – например, если вы захотите изменить местоположение уведомлений или сгруппировать их вместе.

Самостоятельная реализация валидации данных – очень полезный навык. Дополнительную функциональность помогут добавить готовые пакеты, созданные на основе jQuery и JavaScript.

Конструктор пошаговых jQuery форм Timon Step Form

Если вам нужна пошаговая форма, обратите внимание на пакет Timon Step Form. В состав этого набора входит множество готовых элементов форм, а также коллекция эффектов перехода. Это визуальный конструктор, для его использования не нужны навыки программирования. Имеется встроенная jQuery-валидация входных данных.

Smart Forms

Smart Forms представляет собой полнофункциональный фреймворк для создания, как простых, так и сложных форм. В его состав входит поддержка Google reCAPTCHA, проверка номеров телефонов и многое другое. Валидация реализована на jQuery, что делает данный фреймворк отличным выбором.

Just Forms Advanced

Название данного пакета говорит само за себя – это инструмент для создания продвинутых форм. В поставку входит более 110 готовых форм, а сам фреймворк позволяет разработать уникальную форму самостоятельно.

Forms Plus JS

Forms Plus – фреймворк для создания форм с валидацией и вычислениями. Включает в себя более 100 шаблонов для разработки форм. Поддерживает:

  • ввод капчи;
  • выбор даты, времени и цвета;
  • группировку полей;
  • скрытые поля;
  • создание блоков для действий.

Sky Forms

Мы заканчиваем обзор на фреймворке Sky Forms. Данный пакет включает в себя обширный набор стильных элементов, более 300 векторных иконок и множество цветовых схем, поддерживает любую кастомизацию. Предусматривает обработку шести состояний для элементов ввода, включая наведение курсора, фокус и так далее. Формы, созданные с помощью Sky Forms, корректно работают во всех наиболее популярных браузерах.

В этой статье мы рассмотрели, как можно вывести валидацию форм на новый уровень, используя jQuery- плагин. Реализация проверки данных на основе JavaScript предоставляет разработчику дополнительный контроль над вводом, в отличие от базовой HTML-валидации. К примеру, вы сможете без труда добавить к форме сообщения об ошибках, которые будут выводиться, если пользователь введет недопустимые данные в соответствующие поля ввода.

В то же время вы сможете определить, какие действия пользователя и для каких входных элементов плагин должен игнорировать. Я настоятельно рекомендую изучить официальную документацию к плагину и некоторые примеры его использования.

In our previous tutorial, we discussed how to implement basic form validation using some input attributes in HTML5 and a little regex.

In this tutorial, you’ll learn how to use a jQuery plugin to add simple form validation to your website.

Using a jQuery plugin to validate forms serves a lot of purposes. It gives you additional abilities like easily displaying custom error messages and adding conditional logic to jQuery form validation. A validation library can also help you add validation to your HTML forms with minimal or no changes to the markup. The conditions for validity can also be added, removed, or modified at any time with ease.

Getting Started

We’ll use the jQuery Validation Plugin in this tutorial. The plugin offers a lot of features and also helps you define your own validation logic.

Before we can start using the plugin in our fields, we have to include the necessary files in our project. There are two different files to include. The first is the core file, which includes the core features of the plugin, including everything from different validation methods to some custom selectors. The second file contains additional methods to validate inputs like credit card numbers and US-based phone numbers.

You can add these files to your projects via package managers like Bower or NPM. You can also just directly get a CDN link to the files and add them to a script tag on your webpage. Since this is a jQuery-based plugin, you’ll also need to add a link to the jQuery library.

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

Once you’ve added these files, you can start validating any form with the validate method.

Validating Your First Form

You can start using this plugin without making any significant changes to your markup. The only thing that you might have to change is to add an id or class to the form you want to validate if it doesn’t have one already.

Here is the markup of a basic form that we’ll be validating using the jQuery validate plugin.

1
<form id="basic-form" action="" method="post">
2
<p>
3
<label for="name">Name <span>(required, at least 3 characters)</span></label>
4
<input id="name" name="name" minlength="3" type="text" required>
5
</p>
6
<p>
7
<label for="email">E-Mail <span>(required)</span></label>
8
<input id="email" type="email" name="email" required>
9
</p>
10
<p>
11
<input class="submit" type="submit" value="SUBMIT">
12
</p>
13
</form>

We are using the same attributes that we used in our previous HTML5-based form validation tutorial. The form will still do the validation without us adding any JavaScript. However, using the plugin for validation will let us show the error messages right below the invalid input field. We’ll also be able to style the errors however we want.

To start validating the form with this plugin, simply add the following JavaScript code on the webpage:

1
$(document).ready(function() {
2
$("#basic-form").validate();
3
});

This is based on the assumption that you’ve already added the required JavaScript files. Adding those lines of JavaScript will make sure that your form is properly validated and shows all the error messages. Here is a working demo.

The library tries to be as user-friendly as possible by only showing error messages when they’re necessary. For example, if you tab through the name and email fields without actually entering any information, you won’t get any error messages. However, if you try to move to the email field after only entering one character in the name field, you’ll get an error message about entering at least three characters.

The error messages are injected into the DOM using the label element. All of them have an error class, so it’s easy to apply your own styling, as we did in our example. The same is true for invalid inputs, which also get an error class added to them.

Options for the validate() Method

In our previous example, we simply called the validate() method without passing any options to it. However, we can also pass an object to this method along with many options inside that object. The value of these options will determine how the form plugin handles validation, errors, etc.

If you want this plugin to ignore some elements during the validation process, you can do so easily by passing a class or selector to ignore(). The plugin will ignore all form elements with that particular selector when it validates the input.

Add Validation Rules for Input Fields

You can also pass some rules to the validate() method in order to determine how the input values are validated. The value of the rules parameter should be an object with key-value pairs. The key in each case is the name of the element that we want to validate. The value of that key is an object which contains a set of rules which will be used for validation.

You can also add conditional logic to the different fields that you’re validating by using the depends keyword and passing a callback function to it which returns either true or false. Here is an example which uses simple rules to define how the input is validated.

1
$(document).ready(function() {
2
$("#basic-form").validate({
3
rules: {
4
name : {
5
required: true,
6
minlength: 3
7
},
8
age: {
9
required: true,
10
number: true,
11
min: 18
12
},
13
email: {
14
required: true,
15
email: true
16
},
17
weight: {
18
required: {
19
depends: function(elem) {
20
return $("#age").val() > 50
21
}
22
},
23
number: true,
24
min: 0
25
}
26
}
27
});
28
});

In the above code snippet, the keys nameageemail and weight are simply the names of input elements. Each key has an object as its value, and the key-value pairs in the object determine how an input field will be validated.

These validation options are similar to the attributes that you can add in the markup of a form. For example, setting required to true will make the element required for form submission. Setting minlength to a value like 3 will force users to enter at least 3 characters in the text input. There are a few other built-in validation methods which are briefly described on the documentation page.

One thing that you should note in the above code is the use of depends to conditionally make the weight a required field if the age is over 50. This is done by returning true in the callback function if the value entered in the age input field is over 50.

Create Your Own Error Messages

This plugin also allows you to set error messages for different validation rules in a form. You begin by setting the value of the messages key to an object with key-value pairs for the input fields and the corresponding error messages.

Here is an example which will display custom error messages for each input field.

1
messages : {
2
name: {
3
minlength: "Name should be at least 3 characters"
4
},
5
age: {
6
required: "Please enter your age",
7
number: "Please enter your age as a numerical value",
8
min: "You must be at least 18 years old"
9
},
10
email: {
11
email: "The email should be in the format: abc@domain.tld"
12
},
13
weight: {
14
required: "People with age over 50 have to enter their weight",
15
number: "Please enter your weight as a numerical value"
16
}
17
}

Just like rules, messages rely on the name of the input fields. Each of these input fields will accept an object with key-value pairs as its value. The key in each case is the validation rule which has to be followed. The value is simply the error message that you want to display if a particular rule is violated.

For instance, the age input field will trigger the required error message if left blank. However, it will trigger the number error if you enter anything else besides a number in the input field.

One thing you’ll notice is that the plugin will show a generic error message for validation rules where you haven’t supplied a custom error message. Try filling out different values in the following demo, and you’ll see that the custom and generic error messages show up as expected.

Customizing the Appearance of Error Messages

There are times when you might want to add your own classes to valid and invalid input in order to target them more specifically or for better integration with an existing theme.

You can change the classes which are added to valid or invalid input elements using the errorClass and validClass keys. This can help prevent some unwanted clashes due to reusing the same class name. By default, the error class is assigned to every invalid input element and label. The valid class is assigned to every valid input element.

It’s important to remember that setting errorClass to something like fail-alert will remove the error class from the invalid elements. You’ll have to use errorClass: "error fail-alert" to assign multiple classes to the same element. The same goes for validClass.

There are no additional labels added to the form when users enter a valid input. So the classes from validClass are assigned to the valid input element.

The following code snippet builds upon the previous example to add custom CSS classes and styling to invalid and valid elements.

The only additional JavaScript code is used to assign the classes.

1
$(document).ready(function() {
2
$("#basic-form").validate({
3
errorClass: "error fail-alert",
4
validClass: "valid success-alert",
5
// ... More validation code from previous example

Here is the CSS that we’ll use to change the appearance of error messages:

1
label.error.fail-alert {
2
border: 2px solid red;
3
border-radius: 4px;
4
line-height: 1;
5
padding: 2px 0 6px 6px;
6
background: #ffe6eb;
7
}
8
input.valid.success-alert {
9
border: 2px solid #4CAF50;
10
color: green;
11
}

In addition to customizing the error messages, we are also adding our own styling to valid input elements. Here is a CodePen demo to show us the final result.

More Options to Change the Plugin Behavior

You can prevent the plugin from validating input fields on key up, click, and other such events by setting the value of onfocusoutonkeyup, or onclick to false. Keep in mind that boolean true is not a valid value for these keys. This basically means that if you want the plugin to validate or lose focus on a key up event, just leave these options untouched.

You also have the option to change the element in which the error appears. By default, the plugin uses the label element to show all error messages, but you can change it to em or any other element using the errorElement key. The error element itself can then be wrapped in another HTML element using the wrapper key.

These are some of the most common options that you’re likely to use when validating forms. However, there are some other validation options that might come in handy if you want to do something like changing the placement of error messages or grouping them all together.

jQuery Form Validation, JavaScript, and jQuery Forms Found on CodeCanyon

Learning how to do simple form validation by yourself is a great skill to have. But you can get even deeper with these useful jQuery and JavaScript form downloads from CodeCanyon:

1. jQuery Step Wizard With Step Form Builder: Timon Step Form

Timon Step Wizard JavaScript FormTimon Step Wizard JavaScript FormTimon Step Wizard JavaScript Form

If you want to build a multi-step form, the Timon Step Form download is right for you. It features multiple form elements and transition effects that you can use to customize your work. Timon also has a drag-and-drop builder, meaning you can build your form without needing any coding knowledge. It also has jQuery form validation. 

2. Just Forms Advanced

Just Forms Advanced JavaScript FormJust Forms Advanced JavaScript FormJust Forms Advanced JavaScript Form

Reading the name of this purchase will let you know exactly what you’re getting here. But there’s more to these forms than meets the eye. The more than 110 included forms are ready for use, or you can use the framework to make a unique form for yourself.

3. Sky Forms

Sky Forms JavaScript FormSky Forms JavaScript FormSky Forms JavaScript Form

We round out our list with the highly customizable Sky Forms. It comes with modern elements and multiple color schemes. There are also six designed states, including hover, focus, and more. On top of these features and the cross-browser compatibility, there are over 300 vector icons in Sky Forms.

Final Thoughts

In this tutorial, we learned how to take our form validation to the next level using a jQuery plugin. Using simple JavaScript form validation gives us a lot of additional control over basic HTML validation. For instance, you can easily control how and when different error messages appear when an input is filled with invalid values.

Similarly, you can also specify if the plugin should skip validation for some particular elements. I’d strongly recommend that you read the documentation of this plugin and some best practices on how to use it properly.

In our next tutorial, you’ll learn about some more JavaScript-based tools and plugins to help you easily create and validate forms.

And while you’re here, check out some of our other posts on JavaScript forms and form validation!

Did you find this post useful?

Monty Shokeen

Freelancer, Instructor

I am a full-stack developer who also loves to write tutorials. After trying out a bunch of things till my second year of college, I decided to work on my web development skills. Starting with just HTML and CSS, I kept moving forward and gained experience in PHP, JavaScript, and Python.

I usually spend my free time either working on some side projects or traveling around.

Понравилась статья? Поделить с друзьями:
  • Jquery validate error custom
  • Jquery validate error class
  • Jquery validate clear error
  • Jquery success error function
  • Jquery post success error