Advertisement
Guest User

Untitled

a guest
Feb 18th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //user object constructor for when we create the object based on form data
  2. function User(username, email, password, profession, phoneNumber, age, gender, interests) {
  3.     this.username = username;
  4.     this.email = email;
  5.     this.password = password;
  6.     this.profession = profession;
  7.     this.phoneNumber = phoneNumber;
  8.     this.age = age;
  9.     this.gender = gender;
  10.     this.interests = interests;
  11. }
  12. //submit eventhandler
  13. $('form').submit(function(event) {
  14.     //we dont want to actually post it anywhere
  15.     event.preventDefault();
  16.     //all the necessary rules for the form inputs made with regex
  17.     var reg = {
  18.         username: /^[A-Za-z]+(\s)([A-Za-z]+)(\s)/,
  19.         password: /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{7,}/,
  20.         email: /^[A-Za-z]+(\@{1,1})([A-Za-z]+)(\.{1,1})([A-Za-z]+)/,
  21.         phoneNumber: /^\+{0,1}([0-9]{10,12})/,
  22.         age: /^[0-9][0-9]?$|^100$/,
  23.         gender: /male|female/i,
  24.         profession: /\w/i,
  25.         interests: /\w{0,255}/i
  26.     };
  27.     //counting errors
  28.     var errors = 0;
  29.     //foreach input element, check if it the submit button
  30.     //or if the value of the input element matches the rules
  31.     //made with regex. The specific rules names are equal to
  32.     //the matching elements ids, so we can use this keyword
  33.     $('input').each(function() {
  34.         if ($(this).prop('type') != 'submit' && !reg[($(this).prop('id'))].test($(this).val())) {
  35.             $(this).css('background-color', 'red');
  36.             errors++;
  37.         } else {
  38.             $(this).css('background-color', 'white');
  39.         }
  40.     });
  41.     //if all the data was correct, lets create our objecct and print it
  42.     if (errors == 0) {
  43.         var user = new User($('#username').val(), $('#email').val(), $('#password').val(), $('#profession').val(),
  44.             $('#phoneNumber').val(), $('#age').val(), $('#gender').val(), $('#interests').val());
  45.         alert('Success! ' + JSON.stringify(user));
  46.     } else {
  47.         alert('Error, fix the colored input values');
  48.     }
  49. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement