ソースを参照

Working on remote validator

phuoc 12 年 前
コミット
c16d0bc82d

+ 94 - 0
demo/remote.html

@@ -0,0 +1,94 @@
+<!DOCTYPE html>
+<html>
+<head>
+    <title>Bootstrap Validate demo</title>
+
+    <link rel="stylesheet" href="/vendor/bootstrap/css/bootstrap.css"/>
+    <!--[if IE 7]>
+    <link rel="stylesheet" href="/vendor/font-awesome/css/font-awesome-ie7.min.css">
+    <![endif]-->
+    <link rel="stylesheet" href="/vendor/font-awesome/css/font-awesome.min.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/bootstrapvalidate.js"></script>
+</head>
+<body>
+    <div class="container">
+        <div class="row">
+            <!-- form: -->
+            <section>
+                <div class="page-header">
+                    <h1>Bootstrap Validate plugin</h1>
+                </div>
+
+                <div class="col-lg-8 col-lg-offset-2">
+                    <form id="defaultForm" method="post" class="form-horizontal">
+                        <fieldset>
+                            <legend>Remote validator</legend>
+
+                            <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" />
+                                </div>
+                            </div>
+
+                            <div class="form-group">
+                                <label class="col-lg-3 control-label">Email address</label>
+                                <div class="col-lg-5">
+                                    <input type="text" class="form-control" name="email" />
+                                </div>
+                            </div>
+                        </fieldset>
+
+                        <div class="form-group">
+                            <div class="col-lg-9 col-lg-offset-3">
+                                <button type="submit" class="btn btn-primary">Submit</button>
+                            </div>
+                        </div>
+                    </form>
+                </div>
+            </section>
+            <!-- :form -->
+        </div>
+    </div>
+
+<script type="text/javascript">
+$(document).ready(function() {
+    $('#defaultForm').bootstrapValidate({
+        fields: {
+            username: {
+                message: 'The username is not valid',
+                validator: {
+                    notEmpty: {
+                        message: 'The username is required and can\'t be empty'
+                    },
+                    remote: {
+                        url: 'remote.php',
+                        message: 'The username is not available'
+                    }
+                }
+            },
+            email: {
+                validator: {
+                    notEmpty: {
+                        message: 'The email address is required and can\'t be empty'
+                    },
+                    remote: {
+                        url: 'remote.php',
+                        message: 'The email is not available'
+                    }
+                }
+            }
+        },
+        message: 'This value is not valid',
+        iconClass: {
+            valid: 'icon-ok',
+            invalid: 'icon-remove'
+        }
+    });
+});
+</script>
+</body>
+</html>

+ 31 - 0
demo/remote.php

@@ -0,0 +1,31 @@
+<?php
+// This is a sample PHP script which demonstrates the 'remote' validator
+// To make it work, point the web server to root Bootstrap Validate directory
+// and open the remote.html file:
+// http://domain.com/demo/remote.html
+
+sleep(5);
+
+$valid = true;
+
+$users = array(
+    'admin'         => 'admin@domain.com',
+    'administrator' => 'administrator@domain.com',
+    'root'          => 'root@domain.com',
+);
+
+if (isset($_POST['username']) && array_key_exists($_POST['username'], $users)) {
+    $valid = false;
+} else if (isset($_POST['email'])) {
+    $email = $_POST['email'];
+    foreach ($users as $k => $v) {
+        if ($email == $v) {
+            $valid = false;
+            break;
+        }
+    }
+}
+
+echo json_encode(array(
+    'valid' => $valid,
+));

+ 1 - 1
demo/validators.html

@@ -29,7 +29,7 @@
 
                             <div class="form-group">
                                 <label class="col-lg-3 control-label">Username</label>
-                                <div class="col-lg-9">
+                                <div class="col-lg-5">
                                     <input type="text" class="form-control" name="username" />
                                 </div>
                             </div>

+ 74 - 3
dist/js/bootstrapvalidate.js

@@ -23,6 +23,8 @@
         this.$form   = $(form);
         this.options = $.extend({}, $.bootstrapValidator.DEFAULT_OPTIONS, options);
         this.validate();
+        this.xhrRequests = {};
+        this.numPendingRequests = 0;
     };
     $.extend($.bootstrapValidator, {
         /**
@@ -88,11 +90,11 @@
                             if (!$.bootstrapValidator.validator[validatorName]) {
                                 continue;
                             }
-                            var options = validators[validatorName];
-                            if (!$.bootstrapValidator.validator[validatorName].validate(that, fieldElement, options)) {
+                            var isValid = $.bootstrapValidator.validator[validatorName].validate(that, fieldElement, validators[validatorName]);
+                            if (isValid == false) {
                                 that.showError(fieldElement, validatorName);
                                 break;
-                            } else {
+                            } else if (isValid == true) {
                                 that.removeError(fieldElement);
                             }
                         }
@@ -167,6 +169,34 @@
                     $(tip).remove();
                     $fieldElement.removeData('bootstrapValidator.tooltip');
                 }
+            },
+
+            startRequest: function(fieldElement, validatorName, xhr) {
+                var field = $(fieldElement).attr('name');
+
+                this.completeRequest(fieldElement, validatorName);
+
+                if (this.numPendingRequests < 0) {
+                    this.numPendingRequests = 0;
+                }
+                this.numPendingRequests++;
+                if (!this.xhrRequests[field]) {
+                    this.xhrRequests[field] = {};
+                }
+                this.xhrRequests[field][validatorName] = xhr;
+            },
+
+            completeRequest: function(fieldElement, validatorName) {
+                var field = $(fieldElement).attr('name');
+                if (!this.xhrRequests[field] || !this.xhrRequests[field][validatorName]) {
+                    return;
+                }
+
+                var xhr = this.xhrRequests[field][validatorName];
+                this.numPendingRequests--;
+                console.log('---abort---');
+                xhr.abort();
+                delete this.xhrRequests[field][validatorName];
             }
         }
     });
@@ -361,6 +391,47 @@
 }(window.jQuery));
 ;(function($) {
     $.extend($.bootstrapValidator.validator, {
+        remote: {
+            /**
+             * Request a remote server to check the input value
+             *
+             * @param {bootstrapValidator} validateInstance Validate plugin instance
+             * @param {HTMLElement} element
+             * @param {Object} options Can consist of the following keys:
+             * - url
+             * - data [optional]: By default, it will take the value
+             *  {
+             *      <fieldName>: <fieldValue>
+             *  }
+             * - message: The invalid message
+             * @returns {string}
+             */
+            validate: function(validateInstance, element, options) {
+                var value = $(element).val(), name = $(element).attr('name');
+                if (!options.data) {
+                    options.data       = {};
+                    options.data[name] = value;
+                }
+                var xhr = $.ajax({
+                    type: 'POST',
+                    url: options.url,
+                    dataType: 'json',
+                    data: options.data
+                }).success(function(response) {
+                    validateInstance.completeRequest(element, 'remote');
+                    if (response.valid === true || response.valid === 'true') {
+                        validateInstance.showError(element, 'remote');
+                    }
+                });
+                validateInstance.startRequest(element, 'remote', xhr);
+
+                return 'pending';
+            }
+        }
+    });
+}(window.jQuery));
+;(function($) {
+    $.extend($.bootstrapValidator.validator, {
         stringLength: {
             /**
              * Check if the length of element value is less or more than given number

ファイルの差分が大きいため隠しています
+ 1 - 1
dist/js/bootstrapvalidate.min.js


+ 33 - 3
src/js/bootstrapvalidate.js

@@ -23,6 +23,8 @@
         this.$form   = $(form);
         this.options = $.extend({}, $.bootstrapValidator.DEFAULT_OPTIONS, options);
         this.validate();
+        this.xhrRequests = {};
+        this.numPendingRequests = 0;
     };
     $.extend($.bootstrapValidator, {
         /**
@@ -88,11 +90,11 @@
                             if (!$.bootstrapValidator.validator[validatorName]) {
                                 continue;
                             }
-                            var options = validators[validatorName];
-                            if (!$.bootstrapValidator.validator[validatorName].validate(that, fieldElement, options)) {
+                            var isValid = $.bootstrapValidator.validator[validatorName].validate(that, fieldElement, validators[validatorName]);
+                            if (isValid == false) {
                                 that.showError(fieldElement, validatorName);
                                 break;
-                            } else {
+                            } else if (isValid == true) {
                                 that.removeError(fieldElement);
                             }
                         }
@@ -167,6 +169,34 @@
                     $(tip).remove();
                     $fieldElement.removeData('bootstrapValidator.tooltip');
                 }
+            },
+
+            startRequest: function(fieldElement, validatorName, xhr) {
+                var field = $(fieldElement).attr('name');
+
+                this.completeRequest(fieldElement, validatorName);
+
+                if (this.numPendingRequests < 0) {
+                    this.numPendingRequests = 0;
+                }
+                this.numPendingRequests++;
+                if (!this.xhrRequests[field]) {
+                    this.xhrRequests[field] = {};
+                }
+                this.xhrRequests[field][validatorName] = xhr;
+            },
+
+            completeRequest: function(fieldElement, validatorName) {
+                var field = $(fieldElement).attr('name');
+                if (!this.xhrRequests[field] || !this.xhrRequests[field][validatorName]) {
+                    return;
+                }
+
+                var xhr = this.xhrRequests[field][validatorName];
+                this.numPendingRequests--;
+                console.log('---abort---');
+                xhr.abort();
+                delete this.xhrRequests[field][validatorName];
             }
         }
     });

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

@@ -0,0 +1,41 @@
+(function($) {
+    $.extend($.bootstrapValidator.validator, {
+        remote: {
+            /**
+             * Request a remote server to check the input value
+             *
+             * @param {bootstrapValidator} validateInstance Validate plugin instance
+             * @param {HTMLElement} element
+             * @param {Object} options Can consist of the following keys:
+             * - url
+             * - data [optional]: By default, it will take the value
+             *  {
+             *      <fieldName>: <fieldValue>
+             *  }
+             * - message: The invalid message
+             * @returns {string}
+             */
+            validate: function(validateInstance, element, options) {
+                var value = $(element).val(), name = $(element).attr('name');
+                if (!options.data) {
+                    options.data       = {};
+                    options.data[name] = value;
+                }
+                var xhr = $.ajax({
+                    type: 'POST',
+                    url: options.url,
+                    dataType: 'json',
+                    data: options.data
+                }).success(function(response) {
+                    validateInstance.completeRequest(element, 'remote');
+                    if (response.valid === true || response.valid === 'true') {
+                        validateInstance.showError(element, 'remote');
+                    }
+                });
+                validateInstance.startRequest(element, 'remote', xhr);
+
+                return 'pending';
+            }
+        }
+    });
+}(window.jQuery));