yarn add pure-js-validator
// импортируем валиадтор
import { Validator } from 'js-form-validator/js-form-validator.js'
// когда дом готов
document.addEventListener('DOMContentLoaded', () => {
// ищем все формы
const forms = Array.from(document.getElementsByClassName('js-form-ajax'))
// идем по ним
forms.forEach(form => {
// создаем новый инстанс валидатора, подвязав в него нашу форму
const validator = new Validator(form, async function (err, is_valid) {
// если форма валидна
if (is_valid) {
// берем метод с дата-атрибута
const method = form.dataset.method
// берем ссылку с дата-атрибута
const action = form.dataset.action
// получаем все с полей в виде форм даты
const body = new FormData(form)
// преобразовываем в JSON, смотря, что хочет сервер
const value = Object.fromEntries(body.entries());
// создаем запрос на тот action, что нашли
const response = await fetch(action, {
// с тем методом, что нашли. Сокращенная запись method
method: method,
// так надо
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
// превращаем наш обьект с данными в строку. так надо
body: JSON.stringify(value),
});
// если все ок
if (response.ok) {
// проверяем что нам ответил сервер
let result = await response.json();
form.reset()
}
}
})
})
})
Есть 5 (основных) методов, доступные к использованию для запросов на сервер
- GET
- Для получения данных
- нет тела запроса
- Если нужно что-то передать, добавляем гет-параметры в урлу
/api/v1/orders/list/``?status=new
/api/v1/orders/list/``?status=new&offset=15
- POST
- чаще используется для создание чего-либо
- можно оправить что угодно в формате FormData or JSON
- PUT
- используется для ПОЛНОЙ замены изменяемого обьекты, например, личные данные пользователя. То что мы отправим этим методом полностью заменит текущие данные пользователя. Даже, если у пользователя есть телефон, имя и email, а путом мы передали только телефон.
- PATCH
- используется для ЧАСТИЧНОЙ замены изменяемого обьекты, например, личные данные пользователя. То что мы отправим этим методом заменит только те данные пользователя, которые мы отправили. Даже, если у пользователя есть телефон, имя и email, а патчем мы передали только телефон.
- DELETE
- Используется для удаления какой-то сущности на сервере
- нет тела запроса
- Если нужно что-то передать, добавляем в урлу
/api/v1/address/5/delete/
Пример Fetch-запроса, если у нас, не форма, а просто кнопка
<a href='#' class='js-add-to-cart' data-id='5'> add to cart </a>
// ссылка от серверного разработчика, куда отправить запрос, чтобы добавить товар в корзину
const ADD_TO_CART = '/api/v1/cart/add/'
// ищем все кнопки
const btns = Array.from(document.getElementsByClassName('js-add-to-cart'))
// идем по каждой
btns.forEach(btn => {
// навешиваем прослушиватель события клик и делаем ее асинхронной
btn.addEventListener('click', async (e) => {
// предотвращаем нативный поведение ссылки на клик и переход по href
e.preventDefault()
// собираем данные с кнопки, вариантично от требований сервера
const value = {
id: btn.dataset.id
}
// создаем запрос
let response = await fetch(ADD_TO_CART, {
// метод тоже бекендер подскажет
method: 'POST',
// необходимые хедеры
headers: {
'Content-Type': 'application/json;charset=utf-8',
},
// превращаем наш обьект с данными в строку. так надо
body: JSON.stringify(value),
})
console.log(response)
})
})
HTML. Apply «[data-rule]» attribute for each form element that you want to check, or the attribute value, specify the name of one or more rules.
Javascript. You need to create an instance of Validator and pass it two parameters:
Form handle Callback function Callback function has two arguments: err and res. If the form has a validation error, the argument err will be the Object, and if there are no errors - null. Argument res returns a boolean value (true or false) and there is always.
Name | Type | Default | Description |
---|---|---|---|
onAir | Boolean | true | Validation of a current field after the events of «change», «keyup», «blur» |
showErrors | Boolean | true | Show errors automatically |
autoHideErrors | Boolean | false | Auto-hide the error messages |
autoHideErrorsTimeout | Integer | 2000 | Timeout auto-hide error messages |
errorClassName | String | error | Class name for invalid input and error message element |
removeSpaces | Boolean | false | Remove spaces from validation field values before validation |
autoTracking | Boolean | true | Tracking of new elements |
locale | * | String | en |
messages** | Object | { } | Object for custom error messages |
rules*** | Object | { } | Object for custom rules |
*locale - location index for message object.
**messages - an object having the structure:
messages: {
localeName: {
RuleName1: {
empty: 'Message text for empty value',
incorrect: 'Message text for incorrect value'
},
RuleName2: {
empty: 'Message text for empty value',
incorrect: 'Message text for incorrect value'
}
//..
}
}
***rules - an object having the structure:
rules: {
myCustomRulename: function (value, params) {
//Your code here..
//The function should return a boolean value
//true - if the filed
}
}
For the attaching of the rules, you have to add the attribute «[data-rule]» to the form element, and as value is rule name
<input type="text" name="phone" data-rule="phone"/>
For a form element, you can use a few rules that are listed through the separator «|»
<input type="text" name="phone" data-rule="phone|required"/>
Some rules may have parameters. The parameters must be separated by the symbol «-»
<input type="text" name="count" data-rule="between-5-9"/>
Name | Parameters | Example | Description |
---|---|---|---|
notzero | - | notzero | The value can not be zero |
integer | - | integer | Value must be an positive integer |
float | - | float | The value must be a floating point number |
name | - | name | The correct name. Use spaces, letters of the alphabet and the symbol «-» |
lastname | - | lastname | The correct lastname. Use spaces, letters of the alphabet and the symbol «-» |
phone | - | phone | The correct phone number |
- | The correct email address | ||
min | numeric | min-10 | The value must not be less than the value specified in the first parameter |
max | numeric | max-34 | The value must not be greater than the value specified in the first parameter |
between | numeric-numeric | between-5-15 | The value must be between the values specified in the first and the second parameter |
length | numeric-numeric | length-2-100 | The number of characters value must be between the values specified in the first and the second parameter |
minlength | numeric | minlength-8 | The number of characters value must not be less than the value specified in the first parameter |
maxlength | numeric | maxlength-50 | The number of characters value must not be greater than the value |
maxfilesize | numeric-units | maxfilesize-2.5-MB | The size of one or more selected files must not be greater |
fileextension | string-[string] | fileextension-jpg-png-gif | Extension of one or more selected files must match one of the values passed in the parameters |
Name | Required parameters | Optional parameters | Description |
---|---|---|---|
validate | - | HTML Object - Specified validation field | Start validation for all form or specified field. Return value - Object of errors or true |
destroy | - | - | Destroy validator |
reload | - | - | Reload validator |
getFormHandle | - | - | Return current form handle |
getFields | - | - | Return array of all validation fileds |
showErrors | - | HTML Object - Specified validation field | Show errors for all fields or specified field |
hideErrors | - | HTML Object - Specified validation field | Boolean - Remove CSS error classes (See option «errorClassName») Hide errors for all fields or specified field |