1.0.2 • Published 4 years ago

pure-js-validator v1.0.2

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
4 years ago

Pure js validator

  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.

SETTINGS

NameTypeDefaultDescription
onAirBooleantrueValidation of a current field after the events of «change», «keyup», «blur»
showErrorsBooleantrueShow errors automatically
autoHideErrorsBooleanfalseAuto-hide the error messages
autoHideErrorsTimeoutInteger2000Timeout auto-hide error messages
errorClassNameStringerrorClass name for invalid input and error message element
removeSpacesBooleanfalseRemove spaces from validation field values before validation
autoTrackingBooleantrueTracking of new elements
locale*StringenLanguage error messages
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
	}
}

RULES

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"/>

LIST OF RULES

NameParametersExampleDescription
notzero-notzeroThe value can not be zero
integer-integerValue must be an positive integer
float-floatThe value must be a floating point number
name-nameThe correct name. Use spaces, letters of the alphabet and the symbol «-»
lastname-lastnameThe correct lastname. Use spaces, letters of the alphabet and the symbol «-»
phone-phoneThe correct phone number
email-emailThe correct email address
minnumericmin-10The value must not be less than the value specified in the first parameter
maxnumericmax-34The value must not be greater than the value specified in the first parameter
betweennumeric-numericbetween-5-15The value must be between the values ​​specified in the first and the second parameter
lengthnumeric-numericlength-2-100The number of characters value must be between the values ​​specified in the first and the second parameter
minlengthnumericminlength-8The number of characters value must not be less than the value specified in the first parameter
maxlengthnumericmaxlength-50The number of characters value must not be greater than the valuespecifiedinthe first parameter
maxfilesizenumeric-unitsmaxfilesize-2.5-MBThe size of one or more selected files must not be greaterthanthevalue specified in the first parameter
fileextensionstring-stringfileextension-jpg-png-gifExtension of one or more selected files must match one of the values ​​passed in the parameters

API

NameRequired parametersOptional parametersDescription
validate-HTML Object - Specified validation fieldStart 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 fieldShow errors for all fields or specified field
hideErrors-HTML Object - Specified validation fieldBoolean - Remove CSS error classes (See option «errorClassName») Hide errors for all fields or specified field
1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago