Browse Source

update validation

jqh 5 năm trước cách đây
mục cha
commit
7e04602ef4

+ 76 - 0
resources/assets/dcat-admin/main.js

@@ -1335,3 +1335,79 @@ window.require = window.define = window.exports = window.module = undefined;
 
     LA.AssetsLoader = new AssetsLoader;
 })(window);
+
+(function () {
+    /**
+     * 兼容非html5浏览器表单验证功能
+     *
+     * @see https://github.com/liyincheng/html5-form/blob/master/checkValidity.js
+     */
+    function addCheckValidity () {
+        var input = document.createElement("input");
+        if (! input.checkValidity) {
+            HTMLInputElement.prototype.checkValidity = function () {
+                var that = this;
+                //添加checkValidity
+                var m = {
+                    url : /^https?\:\/\/[a-z0-9]+/i,
+                    //date : /^[0-9]{4}\-[0-9]{2}\-[0-9]{2}$/,
+                    email : /^[a-z0-9\.\'\-]+@[a-z0-9\.\-]+$/i,
+                    number : /^[0-9]+(\.[0-9]+)?$/i
+                };
+                // REQUIRED ATTRIBUTES
+                var type  = that.getAttribute('t') || that.getAttribute("type"),
+                    required= (that.getAttribute('required') !== null),
+                    pattern = that.getAttribute('pattern');
+
+                this.validity = {
+                    valueMissing    : required && that.value.length===0,
+                    typeMismatch    : (that.value.length>0) && (type in m) && !that.value.match( m[type] ),
+                    patternMismatch : pattern && (that.value.length>0) && !that.value.match( new RegExp('^'+pattern+'$') )
+                };
+
+                for (var x in that.validity) {
+                    if(x === "valid" && that.validity[x] === true) return true;
+                    if (that.validity[x]) {
+                        that.validity.valid = false;
+                        switch(x){
+                            case "valueMissing":
+                                that.validationMessage = '请填写此项';
+                                break;
+                            case "typeMismatch":
+                                var messages = {
+                                    email: '无效的邮箱格式',
+                                    number: '请输入数字',
+                                    url: '无效的网址格式',
+                                };
+
+                                that.validationMessage = messages[type] || '格式无效';
+                                break;
+                            case "patternMismatch":
+                                that.validationMessage = (this.getAttribute("data-pattern-error") || this.getAttribute("data-error")) || "type mismatch";
+                        }
+                        $(that).trigger('invalid');
+                        return false;
+                    }
+                }
+                return that.validity.valid = true;
+            };
+            HTMLTextAreaElement.prototype.checkValidity = HTMLInputElement.prototype.checkValidity;
+        }
+        //form
+        var form = document.createElement("form");
+        if (!form.checkValidity) {
+            HTMLFormElement.prototype.checkValidity = function(){
+                var $inputs = $(this).find("input, textarea");
+                for (var i = 0; i < $inputs.length; i++) {
+                    if (!$inputs[i].checkValidity()) {
+                        $(this).trigger("invalid");
+                        return false;
+                    }
+                }
+                return true;
+            }
+        }
+    };
+
+    addCheckValidity();
+})();

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
resources/assets/dcat-admin/main.min.js


+ 3 - 0
resources/lang/en/admin.php

@@ -184,5 +184,8 @@ return [
     ],
     'import_extension_confirm' => 'Are you sure import the extension?',
     'selected_must_less_then'  => 'Only supports maximum :num options.',
+    'validation' => [
+        'match' => 'Does not match with :attribute.',
+    ],
     'menu_titles' => [],
 ];

+ 3 - 0
resources/lang/zh-CN/admin.php

@@ -185,5 +185,8 @@ return [
     ],
     'import_extension_confirm' => '确认导入拓展?',
     'selected_must_less_then'  => '最多只能选择:num个选项',
+    'validation' => [
+        'match' => '与 :attribute 不匹配。',
+    ],
     'menu_titles' => [],
 ];

+ 9 - 1
src/Controllers/PermissionController.php

@@ -286,9 +286,17 @@ class PermissionController extends Controller
     {
         $form = new Form(new Permission());
 
+        $permissionTable = config('admin.database.permissions_table');
+        $connection      = config('admin.database.connection');
+
+        $id = $form->getKey();
+
         $form->display('id', 'ID');
 
-        $form->text('slug', trans('admin.slug'))->required();
+        $form->text('slug', trans('admin.slug'))
+            ->required()
+            ->creationRules(['required', "unique:{$connection}.{$permissionTable}"])
+            ->updateRules(['required', "unique:{$connection}.{$permissionTable},slug,$id"]);
         $form->text('name', trans('admin.name'))->required();
 
         $form->multipleSelect('http_method', trans('admin.http.method'))

+ 10 - 1
src/Controllers/RoleController.php

@@ -160,9 +160,18 @@ class RoleController extends Controller
     public function form()
     {
         return Admin::form(new Role('permissions'), function (Form $form) {
+            $roleTable  = config('admin.database.roles_table');
+            $connection = config('admin.database.connection');
+
+            $id = $form->getKey();
+
             $form->display('id', 'ID');
 
-            $form->text('slug', trans('admin.slug'))->required();
+            $form->text('slug', trans('admin.slug'))
+                ->required()
+                ->creationRules(['required', "unique:{$connection}.{$roleTable}"])
+                ->updateRules(['required', "unique:{$connection}.{$roleTable},slug,$id"]);
+
             $form->text('name', trans('admin.name'))->required();
 
             $form->tree('permissions')

+ 13 - 0
src/Form.php

@@ -74,6 +74,7 @@ use Dcat\Admin\Form\Concerns;
  * @method Field\ListField      list($column, $label = '')
  * @method Field\Timezone       timezone($column, $label = '')
  * @method Field\KeyValue       keyValue($column, $label = '')
+ * @method Field\Tel            tel($column, $label = '')
  *
  * @method Field\BootstrapFile          bootstrapFile($column, $label = '')
  * @method Field\BootstrapImage         bootstrapImage($column, $label = '')
@@ -150,6 +151,7 @@ class Form implements Renderable
         'list'           => Field\ListField::class,
         'timezone'       => Field\Timezone::class,
         'keyValue'       => Field\KeyValue::class,
+        'tel'            => Field\Tel::class,
 
         'bootstrapFile'          => Field\BootstrapFile::class,
         'bootstrapImage'         => Field\BootstrapImage::class,
@@ -312,6 +314,17 @@ class Form implements Renderable
         return $this;
     }
 
+    /**
+     * Get specify field.
+     *
+     * @param string $name
+     * @return Field
+     */
+    public function field($name)
+    {
+        return $this->builder->field($name);
+    }
+
     /**
      * @param $column
      * @return $this

+ 1 - 0
src/Form/Builder.php

@@ -642,6 +642,7 @@ class Builder
         $attributes['action'] = $this->getAction();
         $attributes['method'] = Arr::get($options, 'method', 'post');
         $attributes['accept-charset'] = 'UTF-8';
+        $attributes['data-toggle'] = 'validator';
 
         $attributes['class'] = Arr::get($options, 'class');
 

+ 19 - 6
src/Form/Field.php

@@ -9,6 +9,7 @@ use Illuminate\Contracts\Support\Arrayable;
 use Illuminate\Contracts\Support\Renderable;
 use Illuminate\Support\Arr;
 use Illuminate\Support\Fluent;
+use Illuminate\Support\Str;
 use Illuminate\Support\Traits\Macroable;
 
 /**
@@ -16,8 +17,7 @@ use Illuminate\Support\Traits\Macroable;
  */
 class Field implements Renderable
 {
-    use Macroable,
-        Concerns\HasFieldValidator;
+    use Macroable, Concerns\HasFieldValidator;
 
     const FILE_DELETE_FLAG = '_file_del_';
 
@@ -223,7 +223,7 @@ class Field implements Renderable
     /**
      * Get the field element id.
      *
-     * @return string
+     * @return string|array
      */
     public function getElementId()
     {
@@ -239,11 +239,19 @@ class Field implements Renderable
      */
     protected function formatId($column)
     {
+        $random = Str::random(5);
+
         if (is_array($column)) {
-            return str_replace('.', '-', $column);
+            $id = [];
+
+            foreach (str_replace('.', '-', $column) as $k => $v) {
+                $id[$k] = "{$v}-{$random}";
+            }
+
+            return $id;
         }
 
-        return 'form-field-'.str_replace('.', '-', $column);
+        return 'form-field-'.str_replace('.', '-', $column).'-'.$random;
     }
 
     /**
@@ -658,12 +666,17 @@ class Field implements Renderable
     /**
      * Specifies a regular expression against which to validate the value of the input.
      *
+     * @param string $error
      * @param string $regexp
      *
      * @return $this
      */
-    public function pattern($regexp)
+    public function pattern($regexp, $error = null)
     {
+        if ($error) {
+            $this->attribute('data-pattern-error', $error);
+        }
+
         return $this->attribute('pattern', $regexp);
     }
 

+ 1 - 1
src/Form/Field/BootstrapImage.php

@@ -60,7 +60,7 @@ class BootstrapImage extends BootstrapFile
      *
      * @var string
      */
-    protected $rules = 'image';
+    protected $rules = ['image'];
 
     /**
      * @param array|UploadedFile $image

+ 1 - 1
src/Form/Field/BootstrapMultipleImage.php

@@ -18,7 +18,7 @@ class BootstrapMultipleImage extends BootstrapMultipleFile
      *
      * @var string
      */
-    protected $rules = 'image';
+    protected $rules = ['image'];
 
     /**
      * Prepare for each file.

+ 1 - 1
src/Form/Field/Captcha.php

@@ -6,7 +6,7 @@ use Dcat\Admin\Form;
 
 class Captcha extends Text
 {
-    protected $rules = 'required|captcha';
+    protected $rules = ['required', 'captcha'];
 
     protected $view = 'admin::form.captcha';
 

+ 0 - 1
src/Form/Field/DateRange.php

@@ -4,7 +4,6 @@ namespace Dcat\Admin\Form\Field;
 
 use Dcat\Admin\Admin;
 use Dcat\Admin\Form\Field;
-use Psy\Util\Str;
 
 class DateRange extends Field
 {

+ 2 - 2
src/Form/Field/Email.php

@@ -4,11 +4,11 @@ namespace Dcat\Admin\Form\Field;
 
 class Email extends Text
 {
-    protected $rules = 'nullable|email';
+    protected $rules = ['nullable', 'email'];
 
     public function render()
     {
-        $this->prepend('<i class="fa fa-envelope fa-fw"></i>')
+        $this->prepend('<i class="ti-email"></i>')
             ->defaultAttribute('type', 'email');
 
         return parent::render();

+ 1 - 1
src/Form/Field/Image.php

@@ -51,7 +51,7 @@ class Image extends File
 {
     use ImageField;
 
-    protected $rules = 'image';
+    protected $rules = ['image'];
 
     protected $view = 'admin::form.file';
 

+ 1 - 1
src/Form/Field/Ip.php

@@ -6,7 +6,7 @@ use Dcat\Admin\Admin;
 
 class Ip extends Text
 {
-    protected $rules = 'nullable|ip';
+    protected $rules = ['nullable', 'ip'];
 
     /**
      * @see https://github.com/RobinHerbots/Inputmask#options

+ 1 - 1
src/Form/Field/Mobile.php

@@ -19,7 +19,7 @@ class Mobile extends Text
     {
         $this->inputmask($this->options);
 
-        $this->prepend('<i class="fa fa-phone fa-fw"></i>')
+        $this->prepend('<i class="ti-mobile"></i>')
             ->defaultAttribute('style', 'width: 200px');
 
         return parent::render();

+ 14 - 0
src/Form/Field/Tel.php

@@ -0,0 +1,14 @@
+<?php
+
+namespace Dcat\Admin\Form\Field;
+
+class Tel extends Text
+{
+    public function render()
+    {
+        $this->prepend('<i class="fa fa-phone fa-fw"></i>')
+            ->defaultAttribute('type', 'tel');
+
+        return parent::render();
+    }
+}

+ 47 - 0
src/Form/Field/Text.php

@@ -33,6 +33,53 @@ class Text extends Field
         return parent::render();
     }
 
+    /**
+     * Set input type.
+     *
+     * @param string $type
+     * @return $this
+     */
+    public function type(string $type)
+    {
+        return $this->attribute('type', $type);
+    }
+
+    /**
+     * Set "data-match" attribute.
+     *
+     * @see http://1000hz.github.io/bootstrap-validator/
+     *
+     * @param string $field
+     * @param string $error
+     * @return $this
+     */
+    public function confirm(string $field, ?string $error = null, ?string $fieldSelector = null)
+    {
+        if (! $fieldSelector && $this->form) {
+            $fieldSelector = '#'.$this->form->field($field)->getElementId();
+        }
+
+        $attributes = [
+            'data-match'       => $fieldSelector,
+            'data-match-error' => str_replace(':attribute', $field, $error ?: trans('admin.validation.match'))
+        ];
+
+        return $this->attribute($attributes);
+    }
+
+    /**
+     * Set error messages for individual form field.
+     *
+     * @see http://1000hz.github.io/bootstrap-validator/
+     *
+     * @param string $error
+     * @return $this
+     */
+    public function validationError(string $error)
+    {
+        return $this->attribute('data-error', $error);
+    }
+
     /**
      * Add inputmask to an elements.
      *

+ 1 - 1
src/Form/Field/Url.php

@@ -4,7 +4,7 @@ namespace Dcat\Admin\Form\Field;
 
 class Url extends Text
 {
-    protected $rules = 'nullable|url';
+    protected $rules = ['nullable', 'url'];
 
     public function render()
     {

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác