Giter Club home page Giter Club logo

bootstrap-validator's Introduction

Validator, for Bootstrap 3

The Validator plugin offers automatic form validation configurable via mostly HTML5 standard attributes. It also provides an unobtrusive user experience, because nobody likes a naggy form.

Features

  • Configurable via data-api and standard HTML5 attributes
  • Patient to inform user of errors and eager to let them know the errors have been resolved
  • Submit is disabled until the form is valid and all required fields are complete
  • Customizable error messages
  • Custom validator functions
  • Validation of an input field via AJAX

Installation

Documentation

See the project docs at http://1000hz.github.io/bootstrap-validator

Contributing

Found an issue?

Be sure to include a reproducible test case on JS Bin with your report. Here's a template to get started.

Submitting a pull request?

Fork this repo and create a new branch for your patch. Try to adhere to the code style of Bootstrap 3's JS as much as possible. Be sure to add any relevant unit tests. Make sure everything's still ok by running grunt test. Lastly, don't pollute your patch branch with any unrelated changes.

Donating

If you've found this project particularly useful and feel like giving a little back, you can donate what you want via PayPal or Square Cash.

Donate via PayPal Donate via Square Cash

Author

Cina Saffary

Thanks to @mdo and @fat for Bootstrap. <3

Copyright and license

Copyright 2016 Cina Saffary under the MIT license.

bootstrap-validator's People

Contributors

1000hz avatar balcsida avatar chrislawes avatar desfero avatar marten-seemann avatar mrdinckleman avatar n3t avatar nelson6e65 avatar peterdavehello avatar ptica avatar r0ro 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  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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bootstrap-validator's Issues

Language

How do you change language on error messages?
From where are they fetched?

Get rid of HTML5 dependency

Right now the plugin uses HTML5's element.checkValidity() to support all of the standard HTML5 Form validation types. This means they won't work in older browsers.

The plugin should implement all of its own validators to ensure cross-browser support.

Auto append help-block?!

It would be nice if help-block would be appended to parent element automatically so you don't have to put that many empty elements to the form.
Do you think it's possible?

Validate sub groups dans disabled submits

Hi,

first thanks for this script, i'm trying to use it in my project and i'm stuck on it :

I have a form separated in 5 parts ( Twitter collapsed panels ) and in theses part, i have a Next button ( )

  • I added type=submit to them so they are detected by the validator and disabled
    First problem is that then your submit are disabled, you just add "disabled" in this case, the button is css disabled but we can still click on in to go to next part.
    If in firebug i replace "disabled" by "disabled='disabled'" then it works like needed
    So is there a way to add this change in the validator options ?
  • My second question is, how can i make sub validations, be sure all input of first panel are validated before button to next panel is enabled, etc ?

Thanks in advance for your help

data-remote tag

โ“ Hi Guys, is the data-remote tag explained anywhere? I couldn't find it on the documentation, is there any example? I tried a couple of combinations but I can make it work. Thanks in advance!

email validation process

It would seem more constructive for the user experience if the validation of email address happened after the user moved to another field or attempted to submit form. Perhaps a few second delay from the last input. The way it is now user is getting an error before they are completed with input.

example: from your demo if you enter in myname it will show error before you get a chance to put @. Perhaps a slight delay could avoid this?

$('#myForm').submit() called even when form is not validated

Hello!

First of all thank you for validator.js which is a very useful project.

I have a form to validate and for which I have implemented the method $('#myForm').submit() for processing the form. My issue is that this function is called, and so the data processing is performed, when I click on the Submit button even though the form has not been validated (e.g. a required field is left blank).

Which method can I call inside submit() to know whether the form has been validated (and then process the data) or not (and then leave without doing anything)?

Best,
Thomas

Next button not disabled on open panel

If a panel contains some required fields, when the panel is opened (either on first load or other panels toggled), the NEXT button is clickable. I think this should default to disabled if there is required form elements.

Input type="number" validation doesn't work

Hi,

I've checked input of email type or with pattern, it works OK. But the validator doesn't catch error with input type="number" when I enter something other then number (with min, max attributes or without).

Validator to compare two fields

My use case is that I've got to fields with a start and end date. I need to validate those to make sure the start date is not after the end date. How would I go about doing something like that?

(happy to do a fork/PL to make it happen)

hey 1000hz

Can't put validation on select fields of form please help as soon as possible

Validating checkboxes

I have a checkbox array of some elements, with "required" attribute, and the validator need all the checkboxes checked for pass the validation (when I just need at least one checked for my form). How can I define this?

Inline forms not displaying .help-block.with-errors correctly

I have an inline form with ~3 input fields per row, each different. It seems that all the .help-block classes are found within the form-group, and they all display the same error message (e.g. when tabbing out of one, all 3 will display the same error message from that input). Is this something I could work around?

pattern validation message

FYI,

Added a validation message for pattern, dont know if it's best approach.

  if (key == 'native' && typeof $el.attr('pattern') !== typeof undefined)
                    key = 'pattern';

Now i can run

 $('form').validator({
                delay: 500,
                html: false,
                errors: {
                    pattern: "Not valid pattern",
                    match: 'Dont match',
                    minlength: 'lalalala'
                }
            });

At least this method can be applied to more attributes...

Wait for feedback.

Something wrong with the submit button

I met a problem when i used this form validation widget.

var $btn = this.$element.find(':submit')

This code made my all button in the form to be disabled.

I change this code to:
var $btn = this.$element.find('[type="submit"]')

Do you think what i do is right.

Thank you.

I am from China, my english is not very good, so if you don't understand what i said, apologize for that

Use custom validation and use the same color style of your plugin

I add this code

 jQuery.validator.addMethod("orgNotExist", function(value) {
        var in_array = $.inArray(value.toUpperCase(), orgNames);
        if (in_array == -1) {
            return true;
        }else{
            return false;
        }
    }, "This organization url exists before");
    $("#confirmForm1").validate();

but the error appears in blue color, but I want to use red one like your plugin, How can I do that ? ..
can I use custom validator using your plugin ?

Documentary

Hello,
I tried using the validator to validate the inputs for a form that is submitted with a submit-button outside of the form or via pressing the enter key (prevented default behaviour and calling of a customary function).
But from what little documantary is given with the example, I'm not able to find out how to do something like

if (form not valid) {
  do nothing
} else {
  call custom function
}

Calling validator('validate') on the form as is said in the documentation isn't blocking/doesn't keep the function from executing the next line. I've found the "isIncomplete" and "hasErrors" functions in the .js file, but can't seem to figure out how to use them.
A bit more documentation on how to use the validator would be greatly appreciated.

How to change default error (REQUIRED) mesage?

How to change default error message?
I tried this:
$('.page-form').validator(
errors: {
required: "Please enter a valid string..."
}
);
but won't work - still display default/translated message

textarea pattern regexp

Are there any chance to add support for textarea regex validation?
html5 does not support pattern attribute in textarea element
but maybe, this plugin will be able to?

Regex pattern - am I doing it wrong?

Hey thanks for the nice lib.

I am having some trouble with the pattern matching. It might be just my stupidity but it doesn't seem to behave as expected. Got any ideas?

I am trying to match a mobile phone number with a country code prefix.
Basicaaly I want +2222222222 to validate and 2222222222 not fail aswell as any occurence of a non-digit except for the plus at the front. But spaces are cool.

my pattern is /^[\+][\d\s]+$/

my html is

<input id="mobile-number" type="tel" name="user[mobile]" placeholder="#### ####" pattern="/^[+][ds]+$/" data-minlength="8" data-maxlength="20" required="" autocorrect="off" spellcheck="false" autocapitalize="off" class="form-control">

and when I enter a value of +1111111 I get a "Please match the requested format."

However when id the following in the terminal, I get a match

text = $('#mobile-number').val()
text.match(/^[\+][\d\s]+$/)

So am I stupid?

Email Validation Issue

I found a few faults in Email Validation. When i type ' [email protected] ' it a valid email address but when i type ' asa@asda ' bootstrap-validator considers this as a valid email address.
Examples of invalid email addresses considered as valid by ' bootstrap-validator '

  1. asd@asda
  2. [email protected]
  3. [email protected]

I'm not good with javascript but i hope this regex will help.
RegExp(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/)

destroy method

Hi.

For example form is in modal and you need to reset/reinit validation on modal show.

Plugin needs destroy method - .validator("destroy") or smthing like this.

Instantly display a modal when the form is submitted (before validation)

Hi I'm trying to instantly display a modal 'loading' box when the submit button is pressed on a form. I've achieved this by doing the following:

$('form').on('submit', function (event) {
    showLoadingModal();
    if (!event.isDefaultPrevented()) {
        event.preventDefault();
        submitForm(this);
    } else {
        hideLoadingModal();
    }
});

However I'm getting a problem where there is a small gap of time (under a second) between clicking the button and the modal being displayed. I'm assuming this delay is caused by the time taken validating all the fields on the form of which there are quite a lot.

This therefore leads me to believe that the validator 'form submit' is being executed before my code and I should be doing something different to call the showLoadingModal()

issue with data-disable

Hello

I'm trying to use the option data-disable to disble the submit button if there is any error on the form.

However all of these tries didn't work:

Or if there is way to check if the form is validated during submit will help also
$('#NewUserForm').submit(function(e) {

}

Could you help me? Thank you

Remote validation data needs to be URI encoded before submission

We saw this with an email input that had a remote validation:

<input type="email" name="email" data-remote="/api/validate/user" data-remote-error="That email has already been taken">

If the user enters, '[email protected]', that API service will receive a GET request with:

/api/validate/[email protected]

but should be sending:

/api/validate/user?email=user%2B1%40example.com

To fix the issue, you could either call encodeURIComponent on the key and value prior to joining them with the equals sign, or build up an object and let jQuery do the encoding (the approach that I took in the pull request).

Submit button initially disabled but no error messages are shown

Trying your plugin here: http://1000hz.github.io/bootstrap-validator/ if I don't enter any values at all and click submit, it doesn't show any errors (but refuses the submission as expected). I'd expect to show the error for every required field?

If I then click in name, and without typing anything click submit, it marks the name field as required, as expected, and doesn't submit, however, it doesn't highlight any other empty field. This seems to apply to any of the fields in the form.

It's as if you need to click into the input field before it will add the error class to that field when the form is submitted?

Disabled submit with browser autocomplete fields

When I go to a browser autocomplete form and it's valid, the submit bottom is "disabled". When I clic the "body" or change the field focus it turn enabled, but is disabled in the "first view".

radio and checkboxes

Validation of radio bullets don't work.
See PS you see I don't check the last question. So far so good. Then I update the last question and I cannot submit my form. I have to change early questions.

image

image

Uncaught TypeError: Cannot read property 'length' of undefined

I use bootstrap-validator with angular-ui/bootstrap and get an exception: "Uncaught TypeError: Cannot read property 'length' of undefined". It appears if I open modal window and close it without any changes.

    this.defer($el, function () {
      var $group = $el.closest('.form-group')
      var $block = $group.find('.help-block.with-errors')
      var errors = $el.data('bs.validator.errors')

      // Exception is thrown from this line:
      if (!errors.length) return
      // ...
}

Angular template:

<form id="postEditor" data-toggle="validator" role="form">
    <div class="modal-header">
        <h4 class="modal-title">Add new post</h4>
    </div>
    <div class="modal-body">
        <div class="form-group">
            <input ng-model="entity.url" ng-disabled="sending"
                   id="url" type="url" class="form-control" placeholder="URL"
                   data-error="URL address is invalid" autofocus required/>
            <div class="help-block with-errors"></div>
        </div>
        <div class="form-group">
            <input ng-model="entity.tags" ng-disabled="sending"
                   id="tags" type="text" class="form-control" placeholder="Tags"
                   data-error="Enter at least one value" required/>
            <div class="help-block with-errors"></div>
        </div>
    </div>
    <div class="modal-footer">
        <button type="submit" class="btn btn-primary" ng-click="ok()" ng-disabled="sending">Post</button>
        <button type="button" class="btn btn-default" ng-click="cancel()" ng-disabled="sending">Close</button>
    </div>
</form>

pointer-events allowing click

I notices this part

Validator.prototype.toggleSubmit = function () {
    var $btn = this.$element.find('input[type="submit"], button[type="submit"]')
    $btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
      .css({'pointer-events': 'all', 'cursor': 'pointer'})
  }

With this the button gets the class "disabled", using it with bootstrap it prevents the button being clicked but the line.css({'pointer-events': 'all', 'cursor': 'pointer'} adds style="pointer-events': 'all'" allowing to click and sending a blank form; so this should be erased.

ie9 support

is there a way to effect this validation on ie9?

Can I dump an associate array with fields into the fields key of bootstrapvalidator?

I assumed I could do the following (the enabled validator is a custom validator, it works)..

var bv = {
    message: {
        notEmpty: {
            message: 'The street name is required and can\'t be empty.'
        }
    },
    validators:{
        enable_only: {
            enabled: {
                valid: true
            }
        },
        options: {
            enabled: {
                valid: true
            },
            date: {
                format: 'DD/MM/YYYY',
                message: 'The value is not a valid date. The format of the date is DD/MM/YYYY'
            }
        }
    },
    fields: {
        trn: {
            validators: {
                regexp: {
                    regexp: /\d{9}/,
                    message: 'This is not a trn number, \n trn must be nine (9) digits'
                }
            }
        },
        address:{
            location: {
                helpMessage: 'Give the name of the Building/Complex/Apt./Suite/lot # and housing development.',
                validators: {
                    enabled: {
                        valid: true
                    }
                }
            },
            street_num: {
                validators: {
                    enabled: {
                        valid: true
                    }
                }
            },
            street_name: {
                validators: {
                    notEmpty: {
                        message: 'The street name is required and can\'t be empty.'
                    },
                }
            },
            town_district: {
                validators: {
                    notEmpty: {
                        message: 'The town/district is required and can\'t be empty.'
                    },
                }
            },
            post_box: {
                validators: {
                    digits: {
                        message: 'PO box can contain digits only.'
                    }
                }
            },
            post_office: {
                validators: {
                    enabled: {
                        valid: true
                    }
                }
            }
        }
    }
};

In a libs file and then have this in another file...

  $("form[name='address_info']").bootstrapValidator({
        field: bv.fields.address
    });

Any thoughts?

Possible Enhancement

  1. I think it would be nice if you could for Ajax loaded forms. It becomes messy at times when you dynamically load a form on the webpage using PHP, Ajax , Jquery . If you could embed .ajaxStop() and listen for dynamically loaded forms it will be great.

  2. Custom functions for add and remove error on an input field. This will enable developers to add their own validations if necessary
    eg:
    if( !valid() ) { displayError('Some error message'); } else { removeError(); }

Hidden Divs?

I have forms that have divs that are hidden or shown depending on checkbox options.
How can I skip validation for fields in hidden divs?

Thanks,
John

Validating chosen

bootrapValidation v3.1 worked fine validating CHOSEN drop downs. I initialized the JS file as follows:

//* Chosen Configuration & Initialization

 var config = {
    '.chosen-select'           : {},
    '.chosen-select-deselect'  : {allow_single_deselect:true},
    '.chosen-select-no-single' : {disable_search_threshold:10},
    '.chosen-select-no-results': {no_results_text:'No restults found!'},
    '.chosen-select-width'     : {width:"95%"}
  }

  for (var selector in config) {
    $(selector).chosen(config[selector]);
  }

I recently installed the iCheck plugin, which has nothing to do with CHOSEN as far as I can tell, and was having issues getting the checkboxes to validate. I upgraded my bootstrapValidation to v4.2 and initialized iCheck as follows:

//* iCheck iRadio initialization
 $('input').iCheck({
    checkboxClass: 'icheckbox_square-blue',
    radioClass: 'iradio_square-blue',
    focusClass: 'focus',
    increaseArea: '20%'
  });

$('input').on('ifChecked', function(event){
  $('input').iCheck('update');
}); 

I had to add the following JS to revalidate the checkboxes when needed:

  //* Update validator if iCheck field changes
$('input').on('ifChanged', function(event){
    var formId = this.form.id;   //Get the ID attribute of the closest (current) form
    var elementName = $( this ).attr("name");

      $( '#'+formId )  
            // Get the bootstrapValidator instance
            .data('bootstrapValidator')
            // Mark the field as not validated, so it'll be re-validated when the user change date
            .updateStatus( elementName, 'NOT_VALIDATED', null)
            // Validate the field
            .validateField( elementName );
    });

This all worked great for iCheck and validated nicely. However, when I upgraded to boostrapValidation v4.2 my CHOSEN fields no longer would validate. I believe it is related to large amount of changes from bootstrapValidation v3.2 to v4.2. The only other change was adding iCheck plugin. That is why I mentioned that as well.

I need some help in validating CHOSEN fields in bootstrapValidation v4.2.
Here's a snippet of HTML5

...........
City, ZIP, County*
Alamo Beach, 77979, Calhoun Algoa, 77517, Galveston Alvin, 77511, Brazoria Alvin, 77512, Brazoria Amelia, 77707, Jefferson Amsterdam, 77577, Brazoria Anahuac, 77514, Chambers Angleton, 77515, Brazoria Aransas Pass, 78336, Aransas Aransas Pass, 78336, San Patricio Aransas Pass, 78336, Nueces Armstrong, 78338, Kenedy asdfasdfadf

JQuery snippet:
$('#inspection').bootstrapValidator({
message: 'This value is not valid',
//* live: 'enabled',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
structureAddress: {
message: 'The structure address is not valid',
validators: {
notEmpty: {
message: 'The structure address is required!'
}
}
},
structureLocation: {
validators: {
notEmpty: {
message: 'Structure Location is required'
}
}
},
structureCityZipCounty: {
validators: {
notEmpty: {
message: 'Structure city, zip and county are required!'
}
}
},
structCitylimit: {
validators: {
notEmpty: {
message: 'City limit selection is required!'
}
}
},
structCobra: {
validators: {
notEmpty: {
message: 'Structure cobra required! Yes / No'
}
}
}
}
});

Thank you :)

Document that the submit event gets default-prevented when form is invalid

There have been a few issues (#30, #35) asking how to check if the form in invalid in order to prevent some function from running on submit. Since the submit event gets .preventDefault() called on it if the form isn't valid, the docs should call attention to the fact that you can check e.isDefaultPrevented() to return early from a custom submit handler.

Has it a Validated = true feature?

I want to use with jquery ajax. And I need a flag that indicates to current situation of validating form.
For instance;
if($('#myForm').Validate()) {
$.get(function() {
.............
}
}

Add an AJAX endpoint validator

It would be nice to have an ajax validator that sends a request to an endpoint and returns either a success or error response, which gets shown to the user.

Like if you needed to check whether a username was available or something.

Form is always invalid and I'm using AJAX

I am using AJAX to submit a form and the code below is always invalid before I submit the form (Failing) - right now I have an alert on the test page. Not sure why this is happening, only three fields are "required" - name, email, and phone (I only want to submit if the required fields are ok) but it fails even if all fields are filled. I also initialize the form after your js file loads.

Test site: http://tempuswebs.com/clients/itrsphp/contact.php

$(window).on('load', function () {
  $('#contactForm').validator().on('submit', function(e) {
    if(e.isDefaultPrevented())  {
      alert("The form is not completed correctly");
    } else {
      var dataString = $('#contactForm').serialize();
      $.ajax({
          type: 'POST',
          url: 'services/process-email.php',
          data: dataString,
          success: function(res) {
              if (res == 'successful') {
                  window.location=('thanks.php');
              }
              else {
                  //alert("failed");
                  window.location=('thanks.php');
              } 
          },
          error: function () {
            window.location=('thanks.php');
          }
      });
    }
  });
});

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.