Lightweight JavaScript form validation library inspired by CodeIgniter.

Overview

validate.js

validate.js is a lightweight JavaScript form validation library inspired by CodeIgniter.

Features

  • Validate form fields from over a dozen rules
  • No dependencies
  • Customizable Messages
  • Supply your own validation callbacks for custom rules
  • Chainable customization methods for ease of declaration
  • Works in all major browsers, (even IE6!)
  • Modeled off the CodeIgniter form validation API

How to use

    var validator = new FormValidator('example_form', [{
        name: 'req',
        display: 'required',
        rules: 'required'
    }, {
        name: 'alphanumeric',
        rules: 'alpha_numeric'
    }, {
        name: 'password',
        rules: 'required'
    }, {
        name: 'password_confirm',
        display: 'password confirmation',
        rules: 'required|matches[password]'
    }, {
        name: 'email',
        rules: 'valid_email'
    }, {
        name: 'minlength',
        display: 'min length',
        rules: 'min_length[8]'
    }, {
        names: ['fname', 'lname'],
        rules: 'required|alpha'
    }], function(errors) {
        if (errors.length > 0) {
            // Show the errors
        }
    });

Documentation

You can view everything at http://rickharrison.github.com/validate.js

Browserify

It is published to npm under validate-js

npm install validate-js

Plugins

jQuery: https://github.com/magizh/validate_helper

Multi-Language Support

jnhwkim's fork added multi-language support viewable at https://github.com/jnhwkim/validate.js

Chinese - https://github.com/chilijung/validate.js

French - https://github.com/Facyla/validate.js

Brazilian Portuguese - https://github.com/fabiowitt/validate.js

ghit.me

Comments
  • Fixes submit on error

    Fixes submit on error

    Fixes issue #40. When the validation callback throws an error, _validateForm breaks before calling event.preventDefault() but the onSubmit handler catches and suppresses the error. This makes the form submit for seemingly no reason. This pull request moves the try...catch so that an invalid form will not submit when the callback throws an error.

    opened by seep 11
  • submit function in another function

    submit function in another function

    I am trying to use stripe to process a deposit after the top part of a form is validated. It is calling the function, but is submitting right away. Is it possible to pass the onsubmit event through the functions? I'm a noob at javascript. It doesn't seem to be disabling the form.

    new FormValidator('deposit-form', [{ name: 'email', rules: 'required|valid_email' }], function(errors, evt) {

    var SELECTOR_ERRORS = $('.error_box');
    
    if (errors.length > 0) {
        SELECTOR_ERRORS.empty();
    
        SELECTOR_ERRORS.append(errors[0].message);
        SELECTOR_ERRORS.fadeIn(200);
        return false;
    } else {
        SELECTOR_ERRORS.css({ display: 'none' });
        submitDeposit(evt);
    }
    

    });

    function submitDeposit(evt) { // Stripe Error checking Stripe.setPublishableKey('');

    var $deposit_form = $('#deposit-form'); var stripeResponseHandler = function(status, response) { if (response.error) { // Show the errors on the form $deposit_form.find('.error_box').text(response.error.message).css( "display", "inherit" ); } else { // token contains id, last4, and card type var token = response.id; // Insert the token into the form so it gets submitted to the server $deposit_form.append($('').val(token)); // and re-submit $deposit_form.get(0).submit(); } };

    $('#deposit-form').submit(function(evt) {

    Stripe.createToken($deposit_form, stripeResponseHandler);
    
    // Prevent the form from submitting with the default action
    //return false;
    //e.preventDefault();
    if (evt && evt.preventDefault) {
      evt.preventDefault();
    } else if (event) {
      // IE uses the global event variable
      event.returnValue = false;
    }
    

    }); }

    opened by chriscarpenter12 10
  • Made currently validating field accessible to callbacks.

    Made currently validating field accessible to callbacks.

    Adds a 'validating' variable used to make the current field accessible to callbacks. Necessary to implement a 'don't validate if not required clause' in the callback.

    That said, maybe it's worth implementing a switch in the rules string (I think an exclamation mark would be ideal), that makes running the callback conditional on an empty field.

    For example ['required|callback_foo'] = callback foo will always be called ['!callback_foo'] = callback foo will always be called ['other_rules|callback_foo'] = callback foo will only be called if the field is not empty

    edit: Actually probably better the other way around to prevent breaking backwards compatibility of api, so: ['required|callback_foo'] = callback foo will always be called ['callback_foo'] = callback foo will always be called ['other_rules|!callback_foo'] = callback foo will only be called if the field is not empty

    Happy to implement.

    opened by MalucoMarinero 10
  • Errors shown sequenced only 1 by 1 (not shown together)

    Errors shown sequenced only 1 by 1 (not shown together)

    So when i make all fields to be required, e.g:

    • email
    • password
    • fullname

    I tested them by sending empty fields (all of them). But the getErrors only gives first error. If everything empty, the error is on email. If email is not empty, then the error is on password, and so on.

    It's OK. But i wonder, the demo shows all errors (not only 1 by 1). Trying to look into the page source, and i can't find what makes the demo detects all the error.

    opened by ghost 9
  • Added a return false to the _validateForm function if there are any errors

    Added a return false to the _validateForm function if there are any errors

    This is a very small one-liner but I needed it for my application since I have to call _validateForm directly. It would also be nice if there was a way to run that with a more public feel to it as I think I'm using an internal method :P

    opened by mikegioia 9
  • Nothing happens when I click next

    Nothing happens when I click next

    I have a form created with the validation at the end of the page. When I click next, nothing happens in Chrome or Firefox. I am not sure how to debug javascript. Do you know what could be causing this? I'm running locally on MAMP in a php file.

    opened by macaddict89 8
  • Submitting form after validation

    Submitting form after validation

    I'm really sorry - this is the first time I've used JQuery to validate a form and I'm a bit stuck with what to do next.

    So, I've written the HTML. Your (wonderful, thank you!) code validates the fields and displays "All of the fields were successfully validated!" across the top in a nice little DIV. But the form isn't submitted according to the ACTION and METHOD parameters I set. It validates and then does nothing else.

    What command do I need to use to get the form to submit to the handler after validation?

    Thanks so very much in advance.

    opened by kdidymus 7
  • Custom Callback Error message not working in certain scenario

    Custom Callback Error message not working in certain scenario

    Hi! I've been using your validation plugin recently. Its awesome! But there's a problem which I can't figure out. I'd be glad if you could point out the error (if any in my part).

    The callback custom error message is overridden with your error message("An error has occurred with your %s field") when I want to display empty string(setMessage({callback_name}, '')).

    Basically the algorithm and error message is supported and displayed correctly in CodeIgnitor form validation rules but not working in your JS.

    Thanks in advance!

    -------------------------------------------------CODE---------------------------------------------------------------------


    My working code of callback in CodeIgnitor:

    public function valid_age($value) { $currdate = new DateTime(date("Y-m-d")); $selectdate = ''; $post = $this->input->post(); if(!empty($post['usr_dob'])) { if($post['usr_dob'] != 'Select DOB') { $selectdate = new DateTime($post['usr_dob']); $interval = $currdate->diff($selectdate); $interval = abs($interval->format('%r%y')); if ($value != $interval) { $this->form_validation->set_message('valid_age', 'Your %s does not match with your Date of Birth.'); return false; } else return true; } else { $this->form_validation->set_message('valid_age', ''); //This is the part working correctly!! return false; } } else return false; }


    My similar code with your plugin:

    valid.registerCallback('age_check', function(value) { var selectDate = document.getElementById("txt_dob").value; if(selectDate != null) { if(selectDate != 'Select DOB') { var currDate = new Date(); selectDate = new Date(selectDate); var reqdAge = DateDiff.inYears(selectDate, currDate); if(value != reqdAge) { valid.setMessage('age_check', 'Your %s does not match with your Date of Birth.'); return false; } else return true; } else { valid.setMessage('age_check', ''); //This part not working and replaced with your error! return false; } } else {alert("select date is null"); return false; } });


    PS: I've initialized and declared everything and every other function and variable... Your plugin is working correctly otherwise, only that error is being replaced! My current workaround is to display a whitespace instead of empty string in that message(it solves the problem but this is not the hotfix I'm looking for!!! )

    opened by 4coderz 6
  • Help validate.js

    Help validate.js

    How can I display the message I created after verifying if the username and password are correct using php?I want to show that message using the validate.js and not using alert or any other javascript function any help sir?

    opened by countalucard2022 6
  • Form Fires on Error

    Form Fires on Error

    Hey Rick,

    Great library and precisely what I was looking for. I'm having an issue where the form is being submitted even though there is an error firing. Essentially, I leave the form blank, I click submit, validation occurs and adds an error message but it continues to post anyways. Any idea what I'm doing wrong?

    <form action="http://ipaddress/url/addIssue" name="issue-form">
      // Form Logic
      <button class="btn btn-large btn-block btn-success">Add Issue</button>
    </form>
    <script type="text/javascript" src="assets/js/validate-rules.js"></script>
    </body>
    

    validate-rules.js

    var validator = new FormValidator('issue-form', [{
      name: 'title',
      rules: 'required'
    }], function(errors, event) {
      if(errors.length > 0) {
        var selector_errors = $('.error-box');
        if (errors.length > 0) {
          selector_errors.empty();
        for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
          selector_errors.append(errors[i].message + '<br />');
        }
          selector_errors.fadeIn(200);
        }
        if(evt && evt.preventDefault) {
          evt.preventDefault();
        } else if (event) {
          event.returnValue = false;
        } 
      } else {
        copy_values();
      }
    });
    

    Any idea what I'm doing wrong?

    opened by sunnyrjuneja 6
  • Events after validation

    Events after validation

    I'm a javascript newbie, so please excuse my basic question here. I've implemented the validation script so that it correctly validates a few form fields. My question is: How do you tell the script to continue with the POST parameter of submitting the form, after successfully validating the fields?

    Also, I think your instructions could benefit from having notation on including the *onSubmit="return FormValidator()" * code in the form tag.

    Thanks very much in advance.

    opened by jentoast 6
  • Registercallback for input field failing in ajax return

    Registercallback for input field failing in ajax return

    Hi Rick, Trying to check valid zip from database using custom validation rule of an input field on blur. Here is what I am trying, validator.registerCallback('check_validpincode', function(value) { if (checkValidPincode(value)) { return true; } return false; }).setMessage('check_validpincode', 'The Pin Code is invalid.');

    In the remote call section : function checkValidPincode(val) { getNewAjaxResult(val).done(function(d) { $("._ztoken").val(d.token); $('#pincode').removeClass('loading'); if(d.valid == 1){ return true; } else { return false; } }) .fail(function(x){ return false; }); }

    function getNewAjaxResult(val) { // Show the ajax "In progress" spinner // Check from Pin Code records, whether the pincode is valid // If found, return true --> else return false //var arg = 'pincode='+val; var req_path = "./home/checkvalidpincode"; var csrfName = $("._ztoken").attr("name"); var csrfHash = $("._ztoken").val(); // CSRF hash return $.ajax({ url: req_path, type:'POST', dataType: 'json', data: {"pin":val, [csrfName]:csrfHash}, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', headers: {'X-Requested-With': 'XMLHttpRequest'}, beforeSend: function() { $('#pincode').addClass('loading'); } }); }

    I am not able to get the return value from the validator function. Can you please help?

    opened by ZopCoder 0
  • Form validation is bypassed if any exceptions within custom callback

    Form validation is bypassed if any exceptions within custom callback

    Form submits with errors after a validation.

    Issue: For some reason this library does not perform validation correctly whenever classes are added to the form input elements. Update: I have found out that if there are any exceptions thrown from within the custom callback function, the form will submit and bypass the validation!

    Further issue:

    Scenario: I have setup validation options with the second argument, the callback function.

    What makes this very difficult to solve is that the validator ignores the exception, does not report to console.log and continues to redirect the user to the next page. ๐Ÿ‘Ž

    What I suggest to improve this, and help people avoid this issue: In the example documentation, update to something like this:

        // Validation Configuration
        var validator = new FormValidator('myFormId', [
            // ...
            // validation settings
            // ...
        ], function (errors, event) {
            try {
                // Custom code goes here
            } catch (ex) {
                // This is displayed if any major errors occur in the custom code
                console.error('** ERROR IN FORM VALIDATION CALLBACK FUNCTION **');
                console.error(ex);
            }
        });
    
    opened by christoferd 0
Releases(v1.5.1)
  • v1.4(Apr 13, 2014)

  • v1.3(Aug 19, 2013)

    • Fixed an issue where multiple checkboxes could not be validated.
    • There has been an API-breaking change made to callback behavior:
    1. If the required rule is present, a callback will be fired once all other validation rules pass.
    2. If the field is not required and it is empty, the callback will not be called unless condition #3 is met.
    3. A callback will always be called if it is preceded by an '!' i.e. rules: '!callback_myCustomCallback'
    Source code(tar.gz)
    Source code(zip)
Owner
Rick Harrison
Co-Founder of @Meadow (YC W15).
Rick Harrison
Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

Facile is an HTML form validator that is inspired by Laravel's validation style and is designed for simplicity of use.

upjs 314 Dec 26, 2022
Lightweight and powerfull library for declarative form validation

Formurai is a lightweight and powerfull library for declarative form validation Features Setup Usage Options Methods Rules Examples Roadmap Features ?

Illia 49 May 13, 2022
FieldVal - multipurpose validation library. Supports both sync and async validation.

FieldVal-JS The FieldVal-JS library allows you to easily validate data and provide readable and structured error reports. Documentation and Examples D

null 137 Sep 24, 2022
Cross Browser HTML5 Form Validation.

Validatr Cross Browser HTML5 Form Validation. Getting Started View the documentation to learn how to use Validatr. Changelog Version 0.5.1 - 2013-03-1

Jay Morrow 279 Nov 1, 2022
jQuery form validation plugin

jQuery.validationEngine v3.1.0 Looking for official contributors This project has now been going on for more than 7 years, right now I only maintain t

Cedric Dugas 2.6k Dec 23, 2022
HTML 5 & Bootstrap Jquery Form Validation Plugin

HTML 5 & Bootstrap Jquery Form Validation Plugin HTML 5 & Bootstrap 5 & Jquery 3 jbvalidator is a fresh new jQuery based form validation plugin that i

null 37 Dec 6, 2022
A lightweight NodeJS library for strict mime-type validation on streams

A lightweight NodeJS library for strict mime-type validation on streams. It gets a ReadableStream and decets the mime-type using its Magic number and validates it using the provided allowed and forbidden lists; If it's allowed it will pass it to the created WritableStreams and if it's not it will throw an error.

CEO of Death Star 9 Apr 3, 2022
This Login Form made using React hooks , React Js , Css, Json. This form have 3 inputs, it also validate those inputs & it also having length limitations.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Yogesh Sharma 0 Jan 3, 2022
A simple credit cards validation library in JavaScript

creditcard.js A simple credit cards validation library in JavaScript. Project website: https://contaazul.github.io/creditcard.js Install creditcard.js

ContaAzul 323 Jan 7, 2023
v8n โ˜‘๏ธ ultimate JavaScript validation library

The ultimate JavaScript validation library you've ever needed. Dead simple fluent API. Customizable. Reusable. Installation - Documentation - API Intr

Bruno C. Couto 4.1k Dec 30, 2022
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
jQuery Validation Plugin library sources

jQuery Validation Plugin - Form validation made easy The jQuery Validation Plugin provides drop-in validation for your existing forms, while making al

null 10.3k Jan 3, 2023
The most powerful data validation library for JS

joi The most powerful schema description language and data validator for JavaScript. Installation npm install joi Visit the joi.dev Developer Portal f

Sideway Inc. 19.6k Jan 4, 2023
Themis is a validation and processing library that helps you always make sure your data is correct.

Dataffy Themis - The advanced validation library Themis is a validation and processing library that helps you always make sure your data is correct. ยท

Dataffy 14 Oct 27, 2022
:white_check_mark: Easy property validation for JavaScript, Node and Express.

property-validator โœ… Easy property validation for JavaScript, Node and Express Built on top of validator.js, property-validator makes validating reque

Netto Farah 160 Dec 14, 2022
String validation

validator.js A library of string validators and sanitizers. Strings only This library validates and sanitizes strings only. If you're not sure if your

null 20.7k Jan 5, 2023
Dead simple Object schema validation

Yup Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existin

Jason Quense 19.2k Jan 2, 2023
Schema-Inspector is an JSON API sanitisation and validation module.

Schema-Inspector is a powerful tool to sanitize and validate JS objects. It's designed to work both client-side and server-side and to be scalable wit

null 494 Oct 3, 2022
๐Ÿ“ซ Offline email validation - JS or TS

email-seems-valid An offline check to see if an email seems valid. Contains TS or JS packages for browser or Node.js emailSeemsValid('[email protected]')

earnifi 12 Dec 25, 2022