[Release] Universal Form Validation with Javascript (jQuery required)

Dea7h

Subscriber
Joined
Jan 16, 2009
Messages
1,074
Likes
320
#1
Hello everyone! I was writing some codes and I needed to write a form validation for my website. Decided to share it here with you and as it may be nothing new for the majority it may also come in handy for many.

The beauty of it is that you write it once and you can use it anywhere in any given form in your website without repeating a whole bunch of code every single time like the most websites do.

So here comes the main function that you need to put in your main javascript file
PHP:
$(document).ready(function () {
    $('.mainNoticer, .subNoticer').click(function () {
        $('.mainNoticer').fadeOut(200);
    });
});

function displayMessage($str, $type = 'error') {
    var $contain = $('.mainNoticer');
    var $message = $('.subNoticer');
    switch ($type) {
        case 'success':
            $message.empty().append("<font style='color: #14972f;'>" + $str + "</font>");
            break;
        default:
            $message.empty().append("<font style='color: #ff7c7c;'>" + $str + "</font>");
            break;
    }
    $contain.fadeIn(500).css('display', 'flex');
}

function validate($form, $array) {
    var $errors = [];

    $.each($array, function ($name, $rules) {
        $.each($rules, function ($rule, $rule_value) {
            var $value = $($form + ' [name=' + $name + ']').val();
            switch ($rule) {
                case 'range':
                    if ($value.length < $rule_value[0]) {
                        $errors.push("The <b>" + $rules['name'] + "</b> cannot be shorter than <b>" + $rule_value[0] + "</b> characters");
                    } else if ($value.length > $rule_value[1]) {
                        $errors.push("The <b>" + $rules['name'] + "</b> cannot be longer than <b>" + $rule_value[1] + "</b> characters");
                    }
                    break;
                case 'pattern':
                    var pattern = {
                        ALP: /^[a-z]+$/i,
                        NUM: /^[0-9]+$/,
                        ALPNUM: /^[a-z0-9]+$/i,
                        EMAIL: /^[a-z0-9._@-]+$/i
                    };

                    if (!pattern[$rule_value].test($value)) {
                        $errors.push("The <b>" + $rules['name'] + "</b> contains forbidden characters ");
                    }
                    break;
            }
        });
    });

    if (jQuery.isEmptyObject($errors)) {
        return true;
    } else {
        for ($i = 0, $errors_list = ''; $i < $errors.length; $i++) {
            $errors_list += $errors[$i] + '<br />';
        }

        displayMessage($errors_list);
        return false;
    }
}
then you should put these few lines of code in your index.php (or whatever it's called) file for the messages to show

PHP:
<div class="mainNoticer"><div class="subNoticer">#notice</div></div>
and then some style for the message box, put that in your .css file

PHP:
.mainNoticer {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.3);
    font-size: 18px;
    display: none;
    justify-content: center;
    align-items: center;
}

.subNoticer {
    width: 600px;
    height: auto;
    padding: 10px;
    border: 1px solid #2d0808;
    border-radius: 10px;
    background: #620f0f;
}
and now to use it you need to do the following...

Let's say you wanna use it in your register file (even tough it works in any form like your character reset form, stats adder or whatever you like)

There are few things you need to do:

1st you need to change your "Submit" button like that:
Let's say you have something like
PHP:
<input type="submit" value="Register" />
It needs to become like that
PHP:
<input type="button" value="Register" onClick="check()" />
2nd you need to give your <form> an id, something like this:
PHP:
<form action="" method="post" id="register_form">
the important part of this is the id="register_form" ;)

and 3rd you need to put this code in your register.php file to say to the validation what you want it to validate as it follows:
PHP:
<script type="text/javascript">
    function check() {
        if (validate('#register_form', {
            username: { //This stands for your input name attribute on each field (<input type="text" name="username">)
                name: ['Username'], //This is just for the message output, you type whatever you want here
                range: [4, 10],
                pattern: ['ALPNUM']
            },
            password: {//Same with this one... (<input type="password" name="password">)
                name: ['Password'],
                range: [4, 10],
                pattern: ['ALPNUM']
            },
            email: {
                name: ['E-Mail Address'],
                range: [5, 35],
                pattern: ['EMAIL']
            },
            captcha: {
                name: ['Captcha Code'],
                range: [5, 5],
                pattern: ['ALPNUM']
            }
        })) {
            $('#register_form').submit(); //If everything is okay and all the fields are validated you submit the form
        }
    }
</script>
The message output in just for the example it's not even near pretty, feel free to use your own message style whatever it might be...

For the moment there are just 2 validation criteria range and 4 patterns:
ALP = only letters are allowed
NUM = only numbers allowed
ALPNUM = numbers and letters
EMAIL = numbers, letters . - _ and @ are allowed

IMPORTANT you need jQuery (direct download link) for this to work (it's pretty much a must have in any website)

!!NOTICE!!! This is not a final validation, you still need to validate all the fields in your php code

If I have missed anything I will update the thread! I hope someone will have a use for it...
If anyone have any suggestions on how to make it better just let me know ;] Peace <3

Credits: Dea7h (mainly (xax))
 
Likes: NFmc
Joined
Apr 30, 2014
Messages
471
Likes
648
#3
изобщо не виждам смисъл да има някаква филтрация в клиентската част, след като без такава в сървърната така или иначе не може да мине.
 
Joined
Jul 9, 2008
Messages
241
Likes
83
#4
Има смисъл единствено да не ти нулира инпутите, както и че всички клиенти го искат. :D