浏览代码

#14, #57: Use HTML attribute to set options

nghuuphuoc 11 年之前
父节点
当前提交
e6c6b3a349

+ 202 - 0
demo/attribute.html

@@ -0,0 +1,202 @@
+<!DOCTYPE html>
+<html>
+<head>
+    <title>BootstrapValidator demo</title>
+
+    <link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.css"/>
+    <link rel="stylesheet" href="../dist/css/bootstrapValidator.css"/>
+
+    <script type="text/javascript" src="../vendor/jquery/jquery-1.10.2.min.js"></script>
+    <script type="text/javascript" src="../vendor/bootstrap/js/bootstrap.min.js"></script>
+    <script type="text/javascript" src="../dist/js/bootstrapValidator.js"></script>
+</head>
+<body>
+    <div class="container">
+        <div class="row">
+            <!-- form: -->
+            <section>
+                <div class="col-lg-8 col-lg-offset-2">
+                    <div class="page-header">
+                        <h2>Sign up</h2>
+                    </div>
+
+                    <form id="defaultForm" method="post" class="form-horizontal" action="target.php"
+                            data-bv-message="This value is not valid"
+                            data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
+                            data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
+                            data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Full name</label>
+                            <div class="col-lg-4">
+                                <input type="text" class="form-control" name="firstName" placeholder="First name" required data-bv-notempty-message="The first name is required and cannot be empty" />
+                            </div>
+                            <div class="col-lg-4">
+                                <input type="text" class="form-control" name="lastName" placeholder="Last name" required data-bv-notempty-message="The last name is required and cannot be empty" />
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Username</label>
+                            <div class="col-lg-5">
+                                <input type="text" class="form-control" name="username"
+                                        data-bv-message="The username is not valid"
+                                        required data-bv-notempty-message="The username is required and cannot be empty"
+                                        pattern="[a-zA-Z0-9_\.]+" data-bv-regexp-message="The username can only consist of alphabetical, number, dot and underscore"
+                                        data-bv-stringlength="true" data-bv-stringlength-min="6" data-bv-stringlength-max="30" data-bv-stringlength-message="The username must be more than 6 and less than 30 characters long"
+                                        data-bv-different="true" data-bv-different-field="password" data-bv-different-message="The username and password cannot be the same as each other"
+                                        data-bv-remote="true" data-bv-remote-url="remote.php" data-bv-remote-message="The username is not available"
+                                />
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Email address</label>
+                            <div class="col-lg-5">
+                                <input class="form-control" name="email" type="email" data-bv-emailaddress-message="The input is not a valid email address" />
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Password</label>
+                            <div class="col-lg-5">
+                                <input type="password" class="form-control" name="password"
+                                        required data-bv-notempty-message="The password is required and cannot be empty"
+                                        data-bv-identical="true" data-bv-identical-field="confirmPassword" data-bv-identical-message="The password and its confirm are not the same"
+                                        data-bv-different="true" data-bv-different-field="username" data-bv-different-message="The password cannot be the same as username"/>
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Retype password</label>
+                            <div class="col-lg-5">
+                                <input type="password" class="form-control" name="confirmPassword"
+                                        required data-bv-notempty-message="The confirm password is required and cannot be empty"
+                                        data-bv-identical="true" data-bv-identical-field="password" data-bv-identical-message="The password and its confirm are not the same"
+                                        data-bv-different="true" data-bv-different-field="username" data-bv-different-message="The password cannot be the same as username"/>
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Gender</label>
+                            <div class="col-lg-5">
+                                <div class="radio">
+                                    <label>
+                                        <input type="radio" name="gender" value="male" required data-vb-notempty-message="The gender is required" /> Male
+                                    </label>
+                                </div>
+                                <div class="radio">
+                                    <label>
+                                        <input type="radio" name="gender" value="female" /> Female
+                                    </label>
+                                </div>
+                                <div class="radio">
+                                    <label>
+                                        <input type="radio" name="gender" value="other" /> Other
+                                    </label>
+                                </div>
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Birthday</label>
+                            <div class="col-lg-5">
+                                <input type="text" class="form-control" name="birthday" data-bv-date="false" data-bv-date-format="YYYY/MM/DD" data-bv-date-message="The birthday is not valid" /> (YYYY/MM/DD)
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Languages</label>
+                            <div class="col-lg-5">
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="languages[]" value="english" required data-bv-notempty-message="Please specify at least one language you can speak" /> English
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="languages[]" value="french" /> French
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="languages[]" value="german" /> German
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="languages[]" value="russian" /> Russian
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="languages[]" value="other" /> Other
+                                    </label>
+                                </div>
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <label class="col-lg-3 control-label">Programming Languages</label>
+                            <div class="col-lg-5">
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="net" data-bv-choice="true" data-bv-choice-min="2" data-bv-choice-max="$4" /> .Net
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="java" /> Java
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="c" /> C/C++
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="php" /> PHP
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="perl" /> Perl
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="ruby" /> Ruby
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="python" /> Python
+                                    </label>
+                                </div>
+                                <div class="checkbox">
+                                    <label>
+                                        <input type="checkbox" name="programs[]" value="javascript" /> Javascript
+                                    </label>
+                                </div>
+                            </div>
+                        </div>
+
+                        <div class="form-group">
+                            <div class="col-lg-9 col-lg-offset-3">
+                                <button type="submit" class="btn btn-primary">Sign up</button>
+                            </div>
+                        </div>
+                    </form>
+                </div>
+            </section>
+            <!-- :form -->
+        </div>
+    </div>
+
+<script type="text/javascript">
+$(document).ready(function() {
+    $('#defaultForm').bootstrapValidator();
+});
+</script>
+</body>
+</html>

+ 1 - 1
dist/css/bootstrapValidator.min.css

@@ -3,7 +3,7 @@
  *
  * A jQuery plugin to validate form fields. Use with Bootstrap 3
  *
- * @version     v0.3.3
+ * @version     v0.4.0-dev
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT

+ 89 - 13
dist/js/bootstrapValidator.js

@@ -3,7 +3,7 @@
  *
  * A jQuery plugin to validate form fields. Use with Bootstrap 3
  *
- * @version     v0.3.3
+ * @version     v0.4.0-dev
  * @author      https://twitter.com/nghuuphuoc
  * @copyright   (c) 2013 - 2014 Nguyen Huu Phuoc
  * @license     MIT
@@ -55,8 +55,8 @@
         //      validating: 'fa fa-refresh'
         //  }
         feedbackIcons: {
-            valid: null,
-            invalid: null,
+            valid:      null,
+            invalid:    null,
             validating: null
         },
 
@@ -91,11 +91,26 @@
          * Init form
          */
         _init: function() {
-            if (this.options.fields == null) {
-                return;
-            }
+            var that    = this,
+                options = {
+                    message:        this.$form.attr('data-bv-message'),
+                    submitButtons:  this.$form.attr('data-bv-submitbuttons'),
+                    live:           this.$form.attr('data-bv-live'),
+                    fields:         {},
+                    feedbackIcons: {
+                        valid:      this.$form.attr('data-bv-feedbackicons-valid'),
+                        invalid:    this.$form.attr('data-bv-feedbackicons-invalid'),
+                        validating: this.$form.attr('data-bv-feedbackicons-validating')
+                    }
+                },
+                validator,
+                i = 0,
+                v,
+                enabled,
+                optionName,
+                optionValue;
+
 
-            var that = this;
             this.$form
                 // Disable client side validation in HTML 5
                 .attr('novalidate', 'novalidate')
@@ -105,10 +120,47 @@
                     e.preventDefault();
                     that.validate();
                 })
-                .find(this.options.submitButtons)
-                    .on('click', function() {
-                        that.$submitButton = $(this);
-                    });
+                .on('click', this.options.submitButtons, function() {
+                    that.$submitButton = $(this);
+                })
+                // Find all fields which have either "name" or "data-bv-field" attribute
+                .find('[name], [data-bv-field]').each(function() {
+                    var $field = $(this),
+                        field  = $field.attr('name') || $field.attr('data-bv-field');
+                    $field.attr('data-bv-field', field);
+
+                    options.fields[field] = {
+                        message:    $field.attr('data-bv-message'),
+                        container:  $field.attr('data-bv-container'),
+                        selector:   $field.attr('data-bv-selector'),
+                        validators: {}
+                    };
+
+                    for (v in $.fn.bootstrapValidator.validators) {
+                        validator = $.fn.bootstrapValidator.validators[v];
+                        enabled   = $field.attr('data-bv-' + v.toLowerCase()) + '';
+
+                        if (('function' == typeof validator.enableByHtml5
+                                && validator.enableByHtml5($(this))
+                                && (enabled != 'false'))
+                            || ('undefined' == typeof validator.enableByHtml5 && ('' == enabled || 'true' == enabled)))
+                        {
+                            // Try to parse the options via attributes
+                            validator.html5Attributes = validator.html5Attributes || ['message'];
+                            for (i in validator.html5Attributes) {
+                                optionName  = validator.html5Attributes[i];
+                                optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + optionName.toLowerCase());
+                                if (optionValue) {
+                                    options.fields[field]['validators'][v]             = options.fields[field]['validators'][v] || {};
+                                    options.fields[field]['validators'][v][optionName] = optionValue;
+                                }
+                            }
+                        }
+                    }
+                });
+
+            this.options = $.extend(true, this.options, options);
+            console.log(this.options);
 
             for (var field in this.options.fields) {
                 this._initField(field);
@@ -621,6 +673,8 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.choice = {
+        html5Attributes: ['min', 'max'],
+
         /**
          * Check if the number of checked boxes are less or more than a given number
          *
@@ -869,6 +923,8 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.date = {
+        html5Attributes: ['message', 'format'],
+
         /**
          * Return true if the input value is valid date
          *
@@ -990,6 +1046,8 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.different = {
+        html5Attributes: ['message', 'field'],
+
         /**
          * Return true if the input value is different with given field's value
          *
@@ -997,6 +1055,7 @@
          * @param {jQuery} $field Field element
          * @param {Object} options Consists of the following key:
          * - field: The name of field that will be used to compare with current one
+         * - message: The invalid message
          * @returns {Boolean}
          */
         validate: function(validator, $field, options) {
@@ -1107,6 +1166,8 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.identical = {
+        html5Attributes: ['message', 'field'],
+
         /**
          * Check if input value equals to value of particular one
          *
@@ -1138,6 +1199,8 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.ip = {
+        html5Attributes: ['message', 'ipv4', 'ipv6'],
+
         /**
          * Return true if the input value is a IP address.
          *
@@ -1268,6 +1331,11 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.notEmpty = {
+        enableByHtml5: function($field) {
+            var required = $field.attr('required') + '';
+            return ('required' == required || 'true' == required);
+        },
+
         /**
          * Check if input value is empty or not
          *
@@ -1291,14 +1359,16 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.phone = {
+        html5Attributes: ['message', 'country'],
+
         /**
          * Return true if the input value contains a valid US phone number only
          *
          * @param {BootstrapValidator} validator Validate plugin instance
          * @param {jQuery} $field Field element
          * @param {Object} options Consist of key:
+         * - message: The invalid message
          * - country: The ISO 3166 country code
-         *
          * Currently it only supports United State (US) country
          * @returns {Boolean}
          */
@@ -1341,6 +1411,8 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.remote = {
+        html5Attributes: ['message', 'url'],
+
         /**
          * Request a remote server to check the input value
          *
@@ -1443,6 +1515,8 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.stringLength = {
+        html5Attributes: ['message', 'min', 'max'],
+
         /**
          * Check if the length of element value is less or more than given number
          *
@@ -1564,19 +1638,21 @@
 }(window.jQuery));
 ;(function($) {
     $.fn.bootstrapValidator.validators.zipCode = {
+        html5Attributes: ['message', 'country'],
+
         /**
          * Return true if and only if the input value is a valid country zip code
          *
          * @param {BootstrapValidator} validator The validator plugin instance
          * @param {jQuery} $field Field element
          * @param {Object} options Consist of key:
+         * - message: The invalid message
          * - country: The ISO 3166 country code
          *
          * Currently it supports the following countries:
          * - US (United State)
          * - DK (Denmark)
          * - SE (Sweden)
-         *
          * @returns {Boolean}
          */
         validate: function(validator, $field, options) {

文件差异内容过多而无法显示
+ 2 - 2
dist/js/bootstrapValidator.min.js


+ 62 - 10
src/js/bootstrapValidator.js

@@ -54,8 +54,8 @@
         //      validating: 'fa fa-refresh'
         //  }
         feedbackIcons: {
-            valid: null,
-            invalid: null,
+            valid:      null,
+            invalid:    null,
             validating: null
         },
 
@@ -90,11 +90,26 @@
          * Init form
          */
         _init: function() {
-            if (this.options.fields == null) {
-                return;
-            }
+            var that    = this,
+                options = {
+                    message:        this.$form.attr('data-bv-message'),
+                    submitButtons:  this.$form.attr('data-bv-submitbuttons'),
+                    live:           this.$form.attr('data-bv-live'),
+                    fields:         {},
+                    feedbackIcons: {
+                        valid:      this.$form.attr('data-bv-feedbackicons-valid'),
+                        invalid:    this.$form.attr('data-bv-feedbackicons-invalid'),
+                        validating: this.$form.attr('data-bv-feedbackicons-validating')
+                    }
+                },
+                validator,
+                i = 0,
+                v,
+                enabled,
+                optionName,
+                optionValue;
+
 
-            var that = this;
             this.$form
                 // Disable client side validation in HTML 5
                 .attr('novalidate', 'novalidate')
@@ -104,10 +119,47 @@
                     e.preventDefault();
                     that.validate();
                 })
-                .find(this.options.submitButtons)
-                    .on('click', function() {
-                        that.$submitButton = $(this);
-                    });
+                .on('click', this.options.submitButtons, function() {
+                    that.$submitButton = $(this);
+                })
+                // Find all fields which have either "name" or "data-bv-field" attribute
+                .find('[name], [data-bv-field]').each(function() {
+                    var $field = $(this),
+                        field  = $field.attr('name') || $field.attr('data-bv-field');
+                    $field.attr('data-bv-field', field);
+
+                    options.fields[field] = {
+                        message:    $field.attr('data-bv-message'),
+                        container:  $field.attr('data-bv-container'),
+                        selector:   $field.attr('data-bv-selector'),
+                        validators: {}
+                    };
+
+                    for (v in $.fn.bootstrapValidator.validators) {
+                        validator = $.fn.bootstrapValidator.validators[v];
+                        enabled   = $field.attr('data-bv-' + v.toLowerCase()) + '';
+
+                        if (('function' == typeof validator.enableByHtml5
+                                && validator.enableByHtml5($(this))
+                                && (enabled != 'false'))
+                            || ('undefined' == typeof validator.enableByHtml5 && ('' == enabled || 'true' == enabled)))
+                        {
+                            // Try to parse the options via attributes
+                            validator.html5Attributes = validator.html5Attributes || ['message'];
+                            for (i in validator.html5Attributes) {
+                                optionName  = validator.html5Attributes[i];
+                                optionValue = $field.attr('data-bv-' + v.toLowerCase() + '-' + optionName.toLowerCase());
+                                if (optionValue) {
+                                    options.fields[field]['validators'][v]             = options.fields[field]['validators'][v] || {};
+                                    options.fields[field]['validators'][v][optionName] = optionValue;
+                                }
+                            }
+                        }
+                    }
+                });
+
+            this.options = $.extend(true, this.options, options);
+            console.log(this.options);
 
             for (var field in this.options.fields) {
                 this._initField(field);

+ 2 - 0
src/js/validator/choice.js

@@ -1,5 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.validators.choice = {
+        html5Attributes: ['min', 'max'],
+
         /**
          * Check if the number of checked boxes are less or more than a given number
          *

+ 2 - 0
src/js/validator/date.js

@@ -1,5 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.validators.date = {
+        html5Attributes: ['message', 'format'],
+
         /**
          * Return true if the input value is valid date
          *

+ 3 - 0
src/js/validator/different.js

@@ -1,5 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.validators.different = {
+        html5Attributes: ['message', 'field'],
+
         /**
          * Return true if the input value is different with given field's value
          *
@@ -7,6 +9,7 @@
          * @param {jQuery} $field Field element
          * @param {Object} options Consists of the following key:
          * - field: The name of field that will be used to compare with current one
+         * - message: The invalid message
          * @returns {Boolean}
          */
         validate: function(validator, $field, options) {

+ 2 - 0
src/js/validator/identical.js

@@ -1,5 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.validators.identical = {
+        html5Attributes: ['message', 'field'],
+
         /**
          * Check if input value equals to value of particular one
          *

+ 2 - 0
src/js/validator/ip.js

@@ -1,5 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.validators.ip = {
+        html5Attributes: ['message', 'ipv4', 'ipv6'],
+
         /**
          * Return true if the input value is a IP address.
          *

+ 5 - 0
src/js/validator/notEmpty.js

@@ -1,5 +1,10 @@
 (function($) {
     $.fn.bootstrapValidator.validators.notEmpty = {
+        enableByHtml5: function($field) {
+            var required = $field.attr('required') + '';
+            return ('required' == required || 'true' == required);
+        },
+
         /**
          * Check if input value is empty or not
          *

+ 3 - 1
src/js/validator/phone.js

@@ -1,13 +1,15 @@
 (function($) {
     $.fn.bootstrapValidator.validators.phone = {
+        html5Attributes: ['message', 'country'],
+
         /**
          * Return true if the input value contains a valid US phone number only
          *
          * @param {BootstrapValidator} validator Validate plugin instance
          * @param {jQuery} $field Field element
          * @param {Object} options Consist of key:
+         * - message: The invalid message
          * - country: The ISO 3166 country code
-         *
          * Currently it only supports United State (US) country
          * @returns {Boolean}
          */

+ 2 - 0
src/js/validator/remote.js

@@ -1,5 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.validators.remote = {
+        html5Attributes: ['message', 'url'],
+
         /**
          * Request a remote server to check the input value
          *

+ 2 - 0
src/js/validator/stringLength.js

@@ -1,5 +1,7 @@
 (function($) {
     $.fn.bootstrapValidator.validators.stringLength = {
+        html5Attributes: ['message', 'min', 'max'],
+
         /**
          * Check if the length of element value is less or more than given number
          *

+ 3 - 1
src/js/validator/zipCode.js

@@ -1,18 +1,20 @@
 (function($) {
     $.fn.bootstrapValidator.validators.zipCode = {
+        html5Attributes: ['message', 'country'],
+
         /**
          * Return true if and only if the input value is a valid country zip code
          *
          * @param {BootstrapValidator} validator The validator plugin instance
          * @param {jQuery} $field Field element
          * @param {Object} options Consist of key:
+         * - message: The invalid message
          * - country: The ISO 3166 country code
          *
          * Currently it supports the following countries:
          * - US (United State)
          * - DK (Denmark)
          * - SE (Sweden)
-         *
          * @returns {Boolean}
          */
         validate: function(validator, $field, options) {