Skillbooker
Login Register

Jquery and Javascript Validation easy peasy

There are multiple ways to do validation:

  • Server side validationJquery is very robust but it depends often on the page reloading or submitting before you can see if an field validate or not
  • Client side you can validate with Jquery, Javaascript or Html5.
  • The advantage of doing jquery validation above Html 5 validation is that is cross browser and 'it just works' which

Jquery validation is easy peasy as you will see.

First you need to include JQuery on your page plust the jQuery validation scripts. No need downloading them just reference them. Like so.

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script>

JQuery Validate an image size and filetype

The form
 

 <form method="POST" action="/uploadimage" id="loadimage" enctype="multipart/form-data" accept-charset="utf-8">
                <div class="modal-body">
                    <fieldset>
                        <input type="file" name="fileuploads" id="fileuploads">
                        <input type="hidden" id="uploadvalue" value="" name="plu">
                    </fieldset>
                </div>
                <div class="modal-footer">
                    <small><u>Max size</u>: 5mb, <u>File types:</u> jpg, jpeg, jpe, png, gif, bmp, tiff</small>
                    <button type="submit" class="btn btn-primary pull-right">Submit</button>
                </div>
            </form>

the jquery
 

$(document).ready(function () {
    
jQuery(function ($) {
        "use strict";
        $('#loadimage').validate({  //<< the id of the form you are submitting
            rules: {
                fileuploads: { //<< the name of the file you are submitting
                    required: true,
                    extension: "jpg,jpeg,jpe,png,gif,bmp,tiff",
                    filesize: 5,
                }
            },
        });
    });

});

 

validating other form ffields..
the form
 

<form id="myform">
    <input type="text" name="field1" />
    <input type="text" name="field2" />
    <input type="submit" />
</form>

the jquery
 

$(document).ready(function () {

    $('#myform').validate({ // initialize the plugin
        rules: {
            field1: {
                required: true,
                email: true
            },
            field2: {
                required: true,
                minlength: 5
            }
        }
    });

});

other jquery methods available for validating

maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension

Javascript validation

Javascript validation is more work but lighter..
 

$(document).ready(function(){

$('.submit').click(function(){
    validateForm();   
});

function validateForm(){


    var nameReg = /^[A-Za-z]+$/;
    var numberReg =  /^[0-9]+$/;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var names = $('#nameInput').val();
    var company = $('#companyInput').val();
    var email = $('#emailInput').val();
    var telephone = $('#telInput').val();
    var message = $('#messageInput').val();

    var inputVal = new Array(names, company, email, telephone, message);

    var inputMessage = new Array("name", "company", "email address", "telephone number", "message");

     $('.error').hide();

        if(inputVal[0] == ""){
            $('#nameLabel').after('<span class="error"> Please enter your ' + inputMessage[0] + '</span>');
        }
        else if(!nameReg.test(names)){
            $('#nameLabel').after('<span class="error"> Letters only</span>');
        }

        if(inputVal[1] == ""){
            $('#companyLabel').after('<span class="error"> Please enter your ' + inputMessage[1] + '</span>');
        }

        if(inputVal[2] == ""){
            $('#emailLabel').after('<span class="error"> Please enter your ' + inputMessage[2] + '</span>');
        }
        else if(!emailReg.test(email)){
            $('#emailLabel').after('<span class="error"> Please enter a valid email address</span>');
        }

        if(inputVal[3] == ""){
            $('#telephoneLabel').after('<span class="error"> Please enter your ' + inputMessage[3] + '</span>');
        }
        else if(!numberReg.test(telephone)){
            $('#telephoneLabel').after('<span class="error"> Numbers only</span>');
        }

        if(inputVal[4] == ""){
            $('#messageLabel').after('<span class="error"> Please enter your ' + inputMessage[4] + '</span>');
        }       
}   

});

 



Posted on: 2017-03-28 Please login/register to leave comments