Advertisement
Guest User

Untitled

a guest
Nov 5th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function bindValidators() {
  2.     let inputFields = $("form div.form-group input.form-control");
  3.  
  4.     for (let i = 0; i < inputFields.length - 1; i++) {
  5.         let currentField = $(inputFields[i]);
  6.         let nextField = null;
  7.         let name = currentField.attr("name");
  8.         if(name === "user[password]"){
  9.             nextField = $(inputFields[i + 1]);
  10.         }
  11.  
  12.         let validationFunction = getValidationFunction(name);
  13.         bindValidator(validationFunction, currentField, nextField);
  14.     }
  15. }
  16.  
  17. function bindValidator(validationFunction, field, nextField) {
  18.     field.on("input", function () {
  19.         if(validationFunction(field)) {
  20.             field.css("border-color", "green");
  21.         } else {
  22.             field.css("border-color", "red");
  23.         }
  24.     });
  25.  
  26.     if(nextField !== null) {
  27.         nextField.on("input", function () {
  28.             if(validateConfirmPassword(field, nextField)) {
  29.                 nextField.css("border-color", "green");
  30.             } else {
  31.                 nextField.css("border-color", "red");
  32.             }
  33.         });
  34.     }
  35. }
  36.  
  37. function getValidationFunction(fieldName) {
  38.     switch (fieldName) {
  39.         case "user[username]":
  40.             return validateUsername;
  41.         case "user[email]":
  42.             return validateEmail;
  43.         case "user[password]":
  44.             return validatePassword;
  45.     }
  46. }
  47.  
  48. function validateUsername(username) {
  49.     username = username.val().trim();
  50.  
  51.     return /^[^ ]{6,25}$/.test(username);
  52. }
  53.  
  54. function validateEmail(email) {
  55.     email = email.val().trim();
  56.  
  57.     return /^[^ ]+@[a-z][a-z-]*(\.[a-z]+)+$/.test(email);
  58. }
  59.  
  60. function validatePassword(password) {
  61.     password = password.val().trim();
  62.  
  63.     return /^[^ ]{6,25}$/.test(password);
  64. }
  65.  
  66. function validateConfirmPassword(password, confirmPassword) {
  67.     return password.val().localeCompare(confirmPassword.val()) === 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement