Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //npm install --save validate.js
- import validate from 'validate.js';
- import {ERROR} from './constants.js';
- const constraints = {
- email: {
- presence: true,
- email: true
- },
- password: {
- presence: true,
- length: {
- minimum: 6
- },
- format: {
- //at least one uppercase letter, one lowercase letter and one number
- pattern: '^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).+$'
- }
- },
- select: {
- presence: true
- },
- username: {
- presence: true,
- length: {
- minimum: 1,
- maximum: 20
- },
- format: {
- // We don't allow anything that a-z and 0-9
- pattern: '[a-z0-9]+',
- // but we don't care if the username is uppercase or lowercase
- flags: 'i',
- message: 'can only contain a-z and 0-9'
- }
- },
- 'password_confirm': {
- presence: true,
- // and it needs to be equal to the other password
- equality: {
- attribute: 'password',
- message: '^The passwords does not match'
- }
- }
- };
- const form = document.querySelectorAll('.js-form-valid');
- for (let i = 0; i < form.length; i++) {
- form[i].addEventListener('submit', function(e) {
- handleFormSubmit(form[i], e);
- });
- let inputs = form[i].querySelectorAll('input, textarea, select');
- for (let j = 0; j < inputs.length; ++j) {
- inputs[j].addEventListener('change', function() {
- let errors = validate(form[i], constraints) || {};
- handleChangeInput(this, errors[this.name]);
- });
- };
- };
- function handleChangeInput(input, errors) {
- if (errors) {
- input.classList.add(ERROR);
- } else {
- input.classList.remove(ERROR);
- };
- };
- function handleFormSubmit(form, e) {
- let errors = validate(form, constraints) || {};
- let keys = Object.keys(errors);
- for (let i = 0; i < keys.length; i++) {
- let inputs = form.querySelectorAll('input[name="'+keys[i]+'"], select[name="'+keys[i]+'"]');
- for (let j = 0; j < inputs.length; j++) {
- if (inputs[j].name === keys[i]) {
- e.preventDefault();
- inputs[j].classList.add(ERROR);
- };
- };
- };
- if (Object.keys(errors).length === 0) {
- showSuccess(e);
- };
- };
- function showSuccess(e) {
- e.preventDefault();
- alert('success');
- };
Add Comment
Please, Sign In to add comment