sofair-form-validation

Form validation library

Usage no npm install needed!

<script type="module">
  import sofairFormValidation from 'https://cdn.skypack.dev/sofair-form-validation';
</script>

README

Form validation library

INPUT TYPE ENUM

export enum INPUT_TYPE {
  TEXT = 'text',
  NUMBER = 'number',
  SELECT = 'select',
  MULTISELECT = 'multiselect',
  CHECKBOX = 'checkbox',
  RADIO = 'radio',
}

Form Object

const form = {
  name: { name: 'name', type: INPUT_TYPE.TEXT, validation: { required: true, min: 4, max: 5 } },
  phone_number: { name: 'phone_number', type: INPUT_TYPE.NUMBER, validation: { required: true, min: 99, max: 999 } },
  select: { name: 'select', type: INPUT_TYPE.SELECT, validation: { required: true, min: null, max: null } },
  multiselect: { name: 'multiselect', type: INPUT_TYPE.MULTISELECT, validation: { required: true, min: 2, max: 3 } },
};

Values Object

const values = {
  name: 'aaaa',
  phone_number: 150,
  select: 1,
  multiselect: [1, 2, 3, 4]
};

INPUT TYPE VALIDATION ERROR ENUM

export enum INPUT_TYPE_VALIDATION_ERROR {
  UNKNOWN = 'UNKNOWN_INPUT_TYPE',
  INPUT_TEXT_REQUIRED = 'INPUT_TEXT_REQUIRED',
  INPUT_TEXT_MIN = 'INPUT_TEXT_MIN',
  INPUT_TEXT_MAX = 'INPUT_TEXT_MAX',
  INPUT_NUMBER_REQUIRED = 'INPUT_NUMBER_REQUIRED',
  INPUT_NUMBER_MIN = 'INPUT_NUMBER_MIN',
  INPUT_NUMBER_MAX = 'INPUT_NUMBER_MAX',
  INPUT_SELECT_REQUIRED = 'INPUT_SELECT_REQUIRED',
  INPUT_MULTISELECT_REQUIRED = 'INPUT_MULTISELECT_REQUIRED',
  INPUT_MULTISELECT_MIN = 'INPUT_MULTISELECT_MIN',
  INPUT_MULTISELECT_MAX = 'INPUT_MULTISELECT_MAX',
  INPUT_CHECKBOX_REQUIRED = 'INPUT_CHECKBOX_REQUIRED',
  INPUT_RADIO_REQUIRED = 'INPUT_RADIO_REQUIRED',
}

ErrorObject

const errorMessagesObject = {
  code: INPUT_TYPE_VALIDATION_ERROR.INPUT_MULTISELECT_MAX,
  params: { max: 4 }
};

Validate form function -> return Promise<{ formInputId => ErrorObject }>

Validator.validateForm(form, values);

ErrorMessagesObject

const errorMessages = {
  INPUT_TYPE_VALIDATION_ERROR.INPUT_MULTISELECT_MAX: 'max selected items is #*@max@*#'
}

Get error message -> Promise

Validator.errorMessage(errorMessagesObject[formInputId][err.code], err.params);