Code Monkey home page Code Monkey logo

jquery-validator's Introduction

jQuery Validator

I wrote this to be a Laravel bundle, so the installation instructions will approach it from that angle; however, the only real dependency is jQuery, so it should be easy to use in any context.

Installation

Clone this repo into your bundles directory or:

php artisan bundle:install jquery-validator

Now edit your application/bundles.php:

<?php

return array(
    // Other bundles and whizbangs...
    'jquery-validator' => array(
        'auto' => true,
    ),
);

Next, you'll have to publish the bundle's assets:

php artisan bundle:publish

Optional: Enable Form class

In application/config/application.php change the following line:

    'Form' => 'Laravel\\Form',

to

    'Form' => 'Jquery_Validator\\Form',

Usage

You can probably guess that jquery-validator depends on jQuery, so at some point, you'll do something like this:

{{ HTML::script('https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js') }}
{{ HTML::script('bundles/jquery-validator/validator.js') }}

HTML Markup

Feel free to generate your own markup, using data-validations attributes. They are just like the Laravel validation rules.

<form id="myForm" method="POST" action="submit.php">
  <input name="username" type="text" data-validations="required|alpha_dash" />
  <input name="email" type="text" data-validations="email" />
  <input name="password" type="password" data-validations="required|confirmed" />
  <input name="password_confirmation" type="password" />
  <!-- more selects, textareas, etc. -->
  <input name="picture" type="file" data-validations="image" />
  <input name="submit" type="submit" value="Submit" />
</form>

Or, using the Jquery_Validator\Form class, do this:

// Somewhere define validation rules...
$rules = array(
    'username' => 'required|alpha_dash',
    'email'    => 'email',
    'password' => 'required|confirmed',
    'picture'  => 'image',
);

// In the view, pass the rules to Form::open()
{{ Form::open('submit.php', 'POST', array('id' => 'myForm'), null, $rules) }}
    {{ Form::text('username') }}
    {{ Form::text('email') }}
    {{ Form::password('password') }}
    {{ Form::password('password_confirmation') }}
    {{ Form::file('picture') }}
    {{ Form::submit('Submit') }}
{{ Form::close() }}

The data-validations will be set automatically for each input.

Handy. Right? This is a trivial example, but it should be enough to get you started.

JavaScript

So, let's say you want to validate the entire form before "on submit":

$(document).ready(function() {
    $('#myForm').validator({
      events   : 'submit',
      selector : 'input[type!=submit], select, textarea',
      callback : function( elem, valid ) {
          if ( ! valid ) {
              $( elem ).addClass('error');
          }
      }
    });
});

The callback provided is called for each input/select/textarea on which validation is attempted, so the elem in the callback above is the input/select/textarea that contains invalid data - not the parent form.

Want the parent form instead? Use the 'done' callback instead of (or in addition to) the, um..., 'callback' callback.

$(document).ready(function() {
    $('#myForm').validator({
      events   : 'submit',
      selector : 'input[type!=submit], select, textarea',
      done     : function( valid ) {
          if ( ! valid ) {
              $( elem ).addClass('error');
          }
      }
    });
});

But the code above may be bad because the form submits even if the data is invalid. Let's stop the form submission:

$(document).ready(function() {
    $('#myForm').validator({
      events         : 'submit',
      selector       : 'input[type!=submit], select, textarea',
      preventDefault : true,
      callback       : function( elem, valid ) {
          if ( ! valid ) {
              $( elem ).addClass( 'error' );
          }
      }
    });
});

Better. But what if you only want to stop the form's submission when invalid data is present?

$(document).ready(function() {
    $('#myForm').validator({
      events                  : 'submit',
      selector                : 'input[type!=submit], select, textarea',
      preventDefaultIfInvalid : true,
      callback                : function( elem, valid ) {
          if ( ! valid ) {
              $( elem ).addClass( 'error' );
          }
      }
    });
});

Cool. Now, instead of validating the entire form at once, let's do each input.

$(document).ready(function() {
    $('input').validator({
      events   : 'blur change',
      callback : function( elem, valid ) {
          if ( ! valid ) {
              $( elem ).addClass( 'error' );
          }
          else {
              $( elem ).addClass( 'success' );
          }
      }
    });
});

Nice. That's pretty much it. Please enjoy and let me know if you see any bad behavior.

Custom validation rules

If you want to insert custom validation rules on the client side, that's pretty simple, too.

$(document).ready(function() {
    $('input').validator({
      ...
      validate_special: function(attribute, value, parameters) {
          return value == 'special';
      }
    });
});

To trigger the validate_special rule, the markup would look like this:

<input type="text" data-validations="special">

Known issues

  • The validation rules unique and exists will always be valid. The JavaScript in this bundle can't see into your DB, obviously.
  • The active_url rule returns the result of the url rule. There's not a good, easy way to check that the URL is active.

License

MIT license - http://www.opensource.org/licenses/mit-license.php

jquery-validator's People

Contributors

arcadas avatar joecwallace avatar petrot avatar raphaelsaunier avatar spib avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-validator's Issues

[enhancement] Automatically generate "data-validations" fields

It would be great to automatically generate the "data-validations" when passing a validator to the Form. This way we could specify the rules in only one place.

If we would want to implement this change, I think we would have to overwrite the Laravel\Form class so we could pass im a validator end then when generating the fields we would look at the validator to see if there is a data-validations to add.

Laravel 4 package

Hey,

could you create a package for composer for using this library in Laravel 4?
I'd do it myself, but i'm not yet too familiar with Laravel, Composer and Packalyst.

EDIT: I don't even know how to tag this issue as a question. :)

The size attribute with file input type doesn't seem to be working

Hey.
Thanks for such an awesome validator. I have been using this for quite a while now & quite happy about this.

Currently, I am working on a project which needs client side file size validations. I went ahead & used the size validation rule.
It doesn't seem to be working the way it is supposed to.

Is this a known issue? What do you recommend to use?

Thanks.

Parsing elem

Just a quick tip for other people struggling with this. This function is returning 'elem' as a string, not an object. Here's how you parse it:

               callback : function( elem, valid ) {
                    var elem_id = $(elem).attr("id");

                    if ( valid ) {
                        $('span#' +elem_id).html('<img src="/resources/images/icons/tick_circle.png" />');
                    }
                    else {
                        $('span#' +elem_id).html('<img src="/resources/images/icons/cross_circle.png" />');
                    }
                }

ReadMe.md missing "!"

Hey,

in the description on how to valiate on each input, there's missing an "!":

if(valid) {
    $( elem ).addClass( 'error' );
}

should be

if(! valid) {
   ...
}

laravel 4

can you update the installation for composer?

Checkbox validation

Maybe I didn't do something properly, but I wasn't able to validate if a checkbox have been checked or not.

Strangely the code of "validate_accept" (validator.js) was checking if the value of the checkbox was "yes" or "1" (line #190):

return this.validate_match( attribute, value, /^(yes|1)$/ );

But if you create a checkbox this way:

{{ Form::checkbox('cb') }} 

by default the value will be "1", so the code of "validate_accept" will always return true.

What I did to solve the issue:

validate_accepted : function( attribute, value ) {
    return $("input[name='"+attribute+"']").attr('checked');
},

See my commit:

https://github.com/FR6/jquery-validator/commit/7a9fde69c2018e3afe5d64ee541185ebcf42ebef

validate_accepted() ignores checked status on checkboxes

validate_accepted() always returns true because $().val() will return the value attribute regardless of checked status. Perhaps the ":checked" test should be moved before the validate_match test.

validate_accepted : function (attribute, value) {
   return this.validate_match(attribute, value, /^(yes|1)$/) ||
    $("[name=\"" + attribute + "\"]").is(":checked");
},

My html:

    <input type="checkbox" value="1" name="myName" data-validations="accepted">

Validation crashes when using [] brackets in name of input element.

I get a syntax error, unrecognized expression name=mychkbox[] when I submit the form. It is general practice to add square brackets [] to the name of checkboxes to inform PHP that the value is an array of multiple values. However, in validator.js the following code will make JavaScript crash:

if ($("[name=" + attribute + "]").first().is(':radio')) {}
...
return value === $("[name=" + parameters[0] + "]").val();

Instead use:

if ($('[name="' + attribute + '"]').first().is(':radio')) {}
...
return value === $('[name="' + parameters[0] + '"]').val();

All attribute and parameters[0] should be enclosed in double quotes to prevent the error from occurring.

IE7 & 8 errors

There was errors on IE7 and IE8 stoping completely the Javascript.

Using JSHint I corrected some errors and warnings:

FR6@643f553

Length validation fails to flag max length has been exceeded when textarea contains linefeeds.

LF's get converted to CRLF's when the form is submitted. Thus the length on the client side is less than the length on the server side (if textarea contains one or more line feeds). See also http://stackoverflow.com/questions/462348/string-length-differs-from-javascript-to-java-code.

Suppose a database field for storing the textarea contents is set to a text field of max 255 characters. We want to make sure that the textarea contents will fit into that database field. Meaning we should count any line feeds in the textarea twice on the client side.

Solution: Use return value.replace(/\n/g, '\r\n').length; instead of return value.length; in the size() function.

Validation crashes for mutiple select.

Validation crashes when it is possible to make multiple selections using a 'select' element. I have to add the following code in the validate_required() function to make it work.

if ($("[name="" + attribute + ""]").attr('multiple') === 'multiple') {
return $("[name="" + attribute + ""] option:selected").size() > 0;
}

Would it be possible to add custom validations?

Something like this for hexadecimal numbers:

$(document).ready(function() {
    $('#myForm').validator({
      events   : 'submit',
      selector : 'input[type!=submit], select, textarea',
      // Custom validation.
      validations: validate_hexadecimal = function (attribute, value) {
        return this.validate_match(attribute, value, /^[0-9A-F]+$/i);
      };
      callback : function( elem, valid ) {
          if ( ! valid ) {
              $( elem ).addClass('error');
          }
      }
    });
});

A way to know which validation failed?

Is there a way to know which validation failed? E.g. when I have the rules "required" and "email", and I want to know which one didn't go through?

I'd like to use this for printing an error message. Is this already possible?

Thanks in advance.

Validation fails after second submit when new validation rules are added.

Scenario: The first submit of the form fails due to some validation rule. The user then clicks on a radio button that displays another input element previously hidden and a new validation rule is added for that element using some java script. When resubmitting the form the new validation rule is not read into the validation rules.

This is due to jQuery. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery). See http://api.jquery.com/data (and search for 'mutated').

Solution: Use $(this).attr('data-validations') instead of $(this).data('validations').
Thus line 45 should read: var validation_rules = $(this).attr('data-' + attribute),

Errors and warnings.

It would be great if the jquery validator could be enhanced to include warnings too. Thus validating an input element to an error showing it with a red background and preventing to submit the form, and validating an input element to a warning showing it with a yellow background but allowing to submit the form.

At the moment I just copied the validator.js file and renamed it into warnings.js and replaced data-validations by data-warnings. Then I can use data-validations rules for errors and data-warnings rules for warnings. I use $('myform').validator(...) and $('myform').warning(...) to add the logic. Is it possible to pass an argument to jquery validator so it will either validate data-validations (default), data-errors or data-warnings?

Callback once

Hi, I like the plugin, simple. But i wish you can add something like, a done: {} callback,

....
callback: function(el, valid)
{
    ....
},
done: function(valid) // called once
{
    ....
}
....

Thanks is advanced!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.