Javascript form validation plugin

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

FormValidation, the best validation library for JavaScript

form-validation/form-validation

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

The best validation library for JavaScript.

FormValidation

Biggest collection of validators

  • Cover most various types of form field
  • Develop, reuse custom validator
  • Support sync and async validators
  • Plugin based architectue
  • Customize icon
  • Customize error message
  • Customize error message location
  • Customize valid and invalid colors
  • Dynamic field
  • Enable, disable validators on the fly
  • Language packages for error message
  • Support custom message
  • Support custom validators
  • Switch between locales
  • Validate ID and VAT numbers in many countries

Declaring validation rules

form id pl-s">registrationForm"> input name pl-s">userName" data-fv-not-empty pl-s">true" data-fv-not-empty___message pl-s">The username is required" data-fv-string-length pl-s">true" data-fv-string-length___min pl-s">6" data-fv-string-length___message pl-s">The name must be more than 6 characters long" /> form>
FormValidation.formValidation( document.getElementById('registrationForm'),  fields:  userName:  validators:  notEmpty:  message: 'The username is required', >, stringLength:  message: 'The name must be more than 6 characters long', min: 6, >, >, >, >, >, );

Integration with your stack

  • Support native form
  • Support popular CSS frameworks via plugins
  • Support popular JavaScript frameworks
  • Easy to integrate with a framework

Play nice with form libraries

  • Autocomplete
  • Color picker
  • Custom checkbox
  • Custom radio
  • Date picker
  • International telephone input
  • Mask input
  • Rich editor
  • Select
  • Star rating
  • Tag input
  • Time picker
  • Toggle
  • Wizard

Support the latest version of

  • Chrome
  • Firefox
  • Safari
  • Opera
  • Edge
  • Internet Explorer 11

This project is developed by Nguyen Huu Phuoc. I love building products and sharing knowledge.

About

FormValidation, the best validation library for JavaScript

Источник

Javascript form validation plugin

*

Частная коллекция качественных материалов для тех, кто делает сайты

  • Creativo.one2000+ уроков по фотошопу
  • Фото-монстр300+ уроков для фотографов
  • Видео-смайл200+ уроков по видеообработке
  • Жизнь в стиле «Кайдзен» Техники и приемы для гармоничной и сбалансированной жизни

В этой рубрике Вы найдете уроки по Javascript библиотеке jQuery.

Анимация набора текста на jQuery

Сегодня мы бы хотели вам рассказать о библиотеке TypeIt — бесплатном jQuery плагине. С её помощью можно имитировать набор текста. Если всё настроить правильно, то можно добиться очень реалистичного эффекта.

Временная шкала на jQuery

Заметка: Перезагрузка и редирект на JavaScript

Быстрая заметка, где вы сможете найти парочку JS сниппетов для перезагрузки и перенаправления пользователей через JavaScript.

Рисуем диаграмму Ганта

AJAX и PHP: загрузка файла

Stimed — стили в зависимости от времени суток

Интересная библиотека с помощью которой можно задать определённым элементам страницы особые стили в зависимости от времени суток.

Источник

Pristine — Vanilla javascript form validation library

It automatically validates required, min, max, minlength, maxlength attributes and the value of type attributes like email, number and more..

Pristine takes 3 parameters

  • form The form element
  • config An object containing the configuration. Default is bootstrap’s configuration which is
let defaultConfig =  // class of the parent element where the error/success class is added classTo: 'form-group', errorClass: 'has-danger', successClass: 'has-success', // class of the parent element where error text element is appended errorTextParent: 'form-group', // type of element to create for the error text errorTextTag: 'div', // class of the error text element errorTextClass: 'text-help' >; 
  • live A boolean value indicating whether pristine should validate as you type, default is true

Install

$ npm install pristinejs --save 

Custom Validator

pristine.addValidator(nameOrElem, handler, errorMessage, priority, halt); 

Add a custom validator to a field

var pristine = new Pristine(document.getElementById("form1")); var elem = document.getElementById("email"); // A validator to check if the first letter is capitalized pristine.addValidator(elem, function(value)  // here `this` refers to the respective input element if (value.length && value[0] === value[0].toUpperCase()) return true; > return false; >, "The first character must be capitalized", 2, false); 

Add a global custom validator

// A validator to check if the input value is within a specified range // Global validators must be added before creating the pristine instance Pristine.addValidator("my-range", function(value, param1, param2)  // here `this` refers to the respective input element return parseInt(param1)  value && value  parseInt(param2) >, "The value ($) must be between $ and $ ", 5, false); 

Now you can assign it to your inputs like this

 type="text" class="form-control" data-pristine-my-range="10,30" /> 

Add custom error messages

 required data-pristine-required-message="My custom message"/> 

Add an attribute like data-pristine—message with the custom message as value to show custom error messages. You can add custom messages like this for as many validators as you need. Here ValidatorName means required , email , min , max etc.

Built-in validators

Name Usage Description
required required or data-pristine-required Validates required fields
email type=»email» or data-pristine-type=»email» Validates email
number type=»number» or data-pristine-type=»number»
integer data-pristine-type=»integer»
minlength minlength=»10″ or data-pristine-minlength=»10″
maxlength maxlength=»10″ or data-pristine-maxlength=»10″
min min=»20″ or data-pristine-min=»20″
max max=»100″ or data-pristine-max=»100″
pattern pattern=»/[a-z]+$/i» or data-pristine-pattern=»/[a-z]+$/i» , \ must be escaped (replace with \\ )
equals data-pristine-equals=»#field-selector» Check that two fields are equal

API

Pristine(form, config, live)
Constructor

Parameter Default Required? Description
form The form element
config See above The config object
live true Whether pristine should validate as you type

pristine.validate(inputs, silent)
Validate the form or field(s)

Parameter Default Required? Description
inputs When not given, full form is validated. inputs can be one DOM element or a collection of DOM elements returned by document.getElement. , document.querySelector. or even jquery dom
silent false Does not show error error messages when silent is true

pristine.addValidator(elem, fn, msg, priority, halt)
Add a custom validator

Parameter Default Required? Description
elem The dom element where validator is applied to.
fn The function that validates the field. Value of the input field gets passed as the first parameter, and the attribute value (split using comma) as the subsequent parameters. For example, for , validator function get called like fn(«myValue», 10, 20, «dhaka») . Inside the function this refers to the input element
message The message to show when the validation fails. It supports simple templating. $ for the input’s value, $ and so on are for the attribute values. For the above example, $ will get replaced by myValue , $ by 10 , $ by 20 , $ by dhaka . It can also be a function which should return the error string. The values and inputs are available as function arguments
priority 1 Priority of the validator function. The higher the value, the earlier it gets called when there are multiple validators on one field.
halt false Whether to halt validation on the current field after this validation. When true after validating the current validator, rest of the validators are ignored on the current field.

Pristine.addValidator(name, fn, msg, priority, halt)
Add a global custom validator

Parameter Default Required? Description
name A string, the name of the validator, you can then use data-pristine- attribute in form fields to apply this validator
. Other parameters same as above

pristine.getErrors(input)
Get the errors of the form or a specific field

Parameter Default Required? Description
input When input is given, it returns the errors of that input element, otherwise returns all errors of the form as an object, using input element as key and corresponding errors as value. validate() must be called before expecting this method to return correctly.

pristine.addError(input, error)
Add A custom error to an input element

Parameter Default Required? Description
input The input element to which the error should be given
error The error string

pristine.setGlobalConfig(config)
Set the global configuration

Parameter Default Required? Description
config Set the default configuration globally to use in all forms.

Pristine.setLocale(locale)
Set the current locale globally

Parameter Default Required? Description
locale Error messages on new Pristine forms will be displayed according to this locale

Pristine.addMessages(locale, messages)
Set the current locale globally

Parameter Default Required? Description
locale The corresponding locale
messages Object containing validator names as keys and error texts as values

pristine.reset()
Reset the errors in the form

pristine.destroy()
Destroy the pristine object

The goal of this library is not to provide every possible type of validation and thus becoming a bloat. The goal is to provide most common types of validations and a neat way to add custom validators.

Источник

Читайте также:  Php динамический язык программирования
Оцените статью