Validation jQuery: Example

jQuery validation is an extensive library for validating your form data effectively and with ease. It supports different use cases of validations like, conditional-requirements, remote validations, etc.

/**
 * Validates new bid page
 *
 * @author Shiva Bhusal
 *
 */
function InitValidationOfForm(idOfForm) {
    $(idOfForm).validate(
        {
            onkeyup: false,
            success: function (label) {
                var $attributeForOfLabel = $('#' + $(label).attr('for'));
                $attributeForOfLabel.removeClass('validation-error');
                $attributeForOfLabel.parent().find('.custom-combobox').removeClass('validation-error');
            },
            showErrors: function (errorMap) {
                $.each(errorMap, function (key) {
                    var $elementWithNameKey = $('[name=\'' + key + "']");
                    $elementWithNameKey.addClass('validation-error');
                    $elementWithNameKey.parent().find('.custom-combobox').addClass('validation-error');
                });
                this.defaultShowErrors();
            },
            onfocusout: function (e) {
                this.element(e);
            },
            invalidHandler: function (event, validator) {
                if (validator.numberOfInvalids()) {
                    $('html, body').animate({
                        scrollTop: $(validator.errorList[0].element).offset().top
                    }, 200);
                }
            },
            highlight: function (element) {
                $(element).fadeOut(function () {
                    $(element).fadeIn();
                });
            },
            rules: {
                'bid[contact_id]': {
                    required: true
                },
                'bid[project_contact_phone]': {
                    required: true,
                    validatePhone: true
                },
                'bid[project_contact_email]': {
                    required: true,
                    validateEmail: true
                },
                'bid[project_contact_billing_address]': {
                    required: true,
                    validateAddress: true
                },
                'bid[project_name]': {
                    required: true
                },
                'bid[proposed_start_date]': {
                    required: true
                },
                'bid[proposal_expiration_date]': {
                    required: true,
                    proposalExpirationDate: true
                },
                'bid[project_address]': {
                    required: true,
                    validateAddress: true
                },
                'bid[project_specifications_attributes][0][project_specification_detail]': {
                    required: true
                },
                'bid[project_specifications_attributes][0][project_specification_amount]': {
                    required: true
                },
                'bid[tax_rate]': {
                    required: true
                },
                'bid[payment_term]': {
                    required: true
                },
                'bid[terms_and_conditions]': {
                    required: true
                },
                'bid[additional_file]': {
                    accept: 'image/gif,image/png,image/jpeg,image/pjpeg,image/bmp,image/svg+xml,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/plain',
                    filesize: 4194304
                },
                'bid[business_contact_name]': {
                    required: true
                },
                'bid[business_contact_phone]': {
                    required: true,
                    validatePhone: true
                }

            },
            messages: {
                'bid[contact_id]': {
                    required: "Contact name is required"
                },
                'bid[project_contact_phone]': {
                    required: "Phone number is required",
                    validatePhone: 'Please enter a valid Phone Number'
                },
                'bid[project_contact_email]': {
                    required: "Email address is required",
                    validateEmail: "Please enter a valid Email address"
                },
                'bid[project_contact_billing_address]': {
                    required: 'Billing address is required',
                    validateAddress: 'Billing address is required'
                },
                'bid[project_name]': {
                    required: 'Project name is required'
                },
                'bid[proposed_start_date]': {
                    required: 'Proposed start date is required',
                    proposalStartDate: "Proposed start date must be later than yesterday"
                },
                'bid[proposal_expiration_date]': {
                    required: 'Proposal expiration date is required',
                    proposalExpirationDate: "Expiration date cannot be earlier and equal to proposed start date"
                },
                'bid[project_address]': {
                    required: 'Project address is required',
                    validateAddress: 'Project address is required'
                },
                'bid[project_specifications_attributes][0][project_specification_detail]': {
                    required: 'Project specification detail is required'
                },
                'bid[project_specifications_attributes][0][project_specification_amount]': {
                    required: 'Project specification amount is required'
                },
                'bid[payment_term]': {
                    required: 'Payment term is required'
                },
                'bid[tax_rate]': {
                    required: 'Tax rate is required'
                },
                'bid[terms_and_conditions]': {
                    required: 'Terms and Condition is required'
                },
                'bid[additional_file]': {
                    accept: 'Upload only listed file formats',
                    filesize: "Max file size exceeded"
                },
                'bid[business_contact_name]': {
                    required: 'Contact name is required'
                },
                'bid[business_contact_phone]': {
                    required: 'Contact phone number is required',
                    validatePhone: 'Please enter a valid phone number'
                }
            }
        }
    );
}

Conditional Requirement

"quote_request[mileage]": {
  required: function(){
    return $('#quote_request_vehicle_registration_number').val() == '';
  }
}

Remote Validation

rules: {
  "quote_request[vehicle_registration_number]": {
    remote: {
      url: '/quote_requests/validate_reg_num',
      type: 'get',
      data: {reg_number: $('quote_request_vehicle_registration_number').val()}
    }
  },

The serverside response must be a JSON string that must be "true" for valid elements, and can be "false", undefined, or null for invalid elements, using the default error message. If the serverside response is a string, eg. "That name is already taken, try peter123 instead", this string will be displayed as a custom error message in place of the default.

like

def validate_reg_num
  RegistrationApi.new(quote_request_params[:vehicle_registration_number])
  render json: "true"
rescue Savon::SOAPFault
  render json: "false"
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s