Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //user object constructor for when we create the object based on form data
- function User(username, email, password, profession, phoneNumber, age, gender, interests) {
- this.username = username;
- this.email = email;
- this.password = password;
- this.profession = profession;
- this.phoneNumber = phoneNumber;
- this.age = age;
- this.gender = gender;
- this.interests = interests;
- }
- //submit eventhandler
- $('form').submit(function(event) {
- //we dont want to actually post it anywhere
- event.preventDefault();
- //all the necessary rules for the form inputs made with regex
- var reg = {
- username: /^[A-Za-z]+(\s)([A-Za-z]+)(\s)/,
- password: /(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{7,}/,
- email: /^[A-Za-z]+(\@{1,1})([A-Za-z]+)(\.{1,1})([A-Za-z]+)/,
- phoneNumber: /^\+{0,1}([0-9]{10,12})/,
- age: /^[0-9][0-9]?$|^100$/,
- gender: /male|female/i,
- profession: /\w/i,
- interests: /\w{0,255}/i
- };
- //counting errors
- var errors = 0;
- //foreach input element, check if it the submit button
- //or if the value of the input element matches the rules
- //made with regex. The specific rules names are equal to
- //the matching elements ids, so we can use this keyword
- $('input').each(function() {
- if ($(this).prop('type') != 'submit' && !reg[($(this).prop('id'))].test($(this).val())) {
- $(this).css('background-color', 'red');
- errors++;
- } else {
- $(this).css('background-color', 'white');
- }
- });
- //if all the data was correct, lets create our objecct and print it
- if (errors == 0) {
- var user = new User($('#username').val(), $('#email').val(), $('#password').val(), $('#profession').val(),
- $('#phoneNumber').val(), $('#age').val(), $('#gender').val(), $('#interests').val());
- alert('Success! ' + JSON.stringify(user));
- } else {
- alert('Error, fix the colored input values');
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement