PHP 後臺搭建常用類和JS歸納(基於TP)
阿新 • • 發佈:2020-08-10
搭建後臺的時候一些常用的類歸納。基於TP,有些類是要用到PHPMailer等擴充套件,自行git下載即可。
/** * 傳送郵件 * @param $email * @param $title * @param $content * @param null $config * @return bool */ function send_email($email, $title, $content, $config = null) { $config = empty($config) ? unserialize(config('email_server')) : $config; $mail= new \PHPMailer\PHPMailer\PHPMailer(true); // Passing `true` enables exceptions try { //Server settings $mail->SMTPDebug = 0; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = $config['host']; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = $config['username']; // SMTP username $mail->Password = $config['password']; // SMTP password $mail->SMTPSecure = $config['secure']; // Enable TLS encryption, `ssl` also accepted $mail->Port = $config['port']; // TCP port to connect to $mail->CharSet = 'UTF-8'; //Recipients $mail->setFrom($config['username'], $config['fromname']); $mail->addAddress($email); // Name is optional //Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = $title; $mail->Body = $content; if ($mail->send()) { return true; } else { return false; } } catch (Exception $e) { return false; } } /** * 陣列轉xls格式的excel檔案 * @param $data * @param $title * 示例資料 * $data = [ * [NULL, 2010, 2011, 2012], * ['Q1', 12, 15, 21], * ['Q2', 56, 73, 86], * ['Q3', 52, 61, 69], * ['Q4', 30, 32, 10], * ]; * @throws PHPExcel_Exception * @throws PHPExcel_Reader_Exception * @throws PHPExcel_Writer_Exception */ function export_excel($data, $title) { // 最長執行時間,php預設為30秒,這裡設定為0秒的意思是保持等待知道程式執行完成 ini_set('max_execution_time', '0'); $phpexcel = new PHPExcel(); // Set properties 設定檔案屬性 $properties = $phpexcel->getProperties(); $properties->setCreator("Boge");//作者是誰 可以不設定 $properties->setLastModifiedBy("Boge");//最後一次修改的作者 $properties->setTitle($title);//設定標題 $properties->setSubject('測試');//設定主題 $properties->setDescription("備註");//設定備註 $properties->setKeywords("關鍵詞");//設定關鍵詞 $properties->setCategory("類別");//設定類別 $sheet = $phpexcel->getActiveSheet(); $sheet->fromArray($data); $sheet->setTitle('Sheet1'); // 設定sheet名稱 $phpexcel->setActiveSheetIndex(0); header('Content-Type: application/vnd.ms-excel'); header("Content-Disposition: attachment;filename=" . $title . ".xls"); header('Cache-Control: max-age=0'); header('Cache-Control: max-age=1'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified header('Cache-Control: cache, must-revalidate'); // HTTP/1.1 header('Pragma: public'); // HTTP/1.0 $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5'); $objwriter->save('php://output'); exit; } /** * http請求 * @param string $url 請求的地址 * @param array $data 傳送的引數 */ function https_request($url, $data = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); if (!empty($data)) { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } /** * 格式化位元組大小 * @param number $size 位元組數 * @param string $delimiter 數字和單位分隔符 * @return string 格式化後的帶單位的大小 */ function format_bytes($size, $delimiter = '') { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024; return round($size, 2) . $delimiter . $units[$i]; } /** * 把json字串轉陣列 * @param json $p * @return array */ function json_to_array($p) { if (mb_detect_encoding($p, array('ASCII', 'UTF-8', 'GB2312', 'GBK')) != 'UTF-8') { $p = iconv('GBK', 'UTF-8', $p); } return json_decode($p, true); } // 生成唯一訂單號 function build_order_no() { return date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } /** * 獲取隨機位數數字 * @param integer $len 長度 * @return string */ function rand_number($len = 6) { return substr(str_shuffle(str_repeat('0123456789', 10)), 0, $len); } /** * 驗證手機號是否正確 * @param number $mobile */ function check_mobile($mobile) { if (!is_numeric($mobile)) { return false; } return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$|^19[\d]{9}$#', $mobile) ? true : false; } /** * 驗證固定電話格式 * @param string $tel 固定電話 * @return boolean */ function check_tel($tel) { $chars = "/^([0-9]{3,4}-)?[0-9]{7,8}$/"; if (preg_match($chars, $tel)) { return true; } else { return false; } } /** * 驗證郵箱格式 * @param string $email 郵箱 * @return boolean */ function check_email($email) { $chars = "/^[0-9a-zA-Z]+(?:[\_\.\-][a-z0-9\-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+$/i"; if (preg_match($chars, $email)) { return true; } else { return false; } } /** * 驗證QQ號碼是否正確 * @param number $mobile */ function check_qq($qq) { if (!is_numeric($qq)) { return false; } return true; } /** * 驗證密碼長度 * @param string $password 需要驗證的密碼 * @param int $min 最小長度 * @param int $max 最大長度 */ function check_password($password, $min, $max) { if (strlen($password) < $min || strlen($password) > $max) { return false; } return true; } /** * 是否在微信中 */ function in_wechat() { return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false; } /** * 配置值解析成陣列 * @param string $value 配置值 * @return array|string */ function parse_attr($value) { if (is_array($value)) { return $value; } $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n")); if (strpos($value, ':')) { $value = array(); foreach ($array as $val) { list($k, $v) = explode(':', $val); $value[$k] = $v; } } else { $value = $array; } return $value; } /** * 陣列層級縮排轉換 * @param array $array 源陣列 * @param int $pid * @param int $level * @return array */ function list_to_level($array, $pid = 0, $level = 1) { static $list = []; foreach ($array as $k => $v) { if ($v['pid'] == $pid) { $v['level'] = $level; $list[] = $v; unset($array[$k]); list_to_level($array, $v['id'], $level + 1); } } return $list; } /** * 把返回的資料集轉換成Tree * @param array $list 要轉換的資料集 * @param string $pid parent標記欄位 * @param string $level level標記欄位 * @return array * @author 麥當苗兒 <[email protected]> */ function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0) { // 建立Tree $tree = array(); if (is_array($list)) { // 建立基於主鍵的陣列引用 $refer = array(); foreach ($list as $key => $data) { $refer[$data[$pk]] = &$list[$key]; } foreach ($list as $key => $data) { // 判斷是否存在parent $parentId = $data[$pid]; if ($root == $parentId) { $tree[] = &$list[$key]; } else { if (isset($refer[$parentId])) { $parent = &$refer[$parentId]; $parent[$child][] = &$list[$key]; } } } } return $tree; } /** * 將list_to_tree的樹還原成列表 * @param array $tree 原來的樹 * @param string $child 孩子節點的鍵 * @param string $order 排序顯示的鍵,一般是主鍵 升序排列 * @param array $list 過渡用的中間陣列, * @return array 返回排過序的列表陣列 * @author yangweijie <[email protected]> */ function tree_to_list($tree, $child = 'children', $order = 'id', &$list = array()) { if (is_array($tree)) { $refer = array(); foreach ($tree as $key => $value) { $reffer = $value; if (isset($reffer[$child])) { unset($reffer[$child]); tree_to_list($value[$child], $child, $order, $list); } $list[] = $reffer; } $list = list_sort_by($list, $order, $sortby = 'asc'); } return $list; } /** * 對查詢結果集進行排序 * @access public * @param array $list 查詢結果 * @param string $field 排序的欄位名 * @param array $sortby 排序型別 * asc正向排序 desc逆向排序 nat自然排序 * @return array */ function list_sort_by($list, $field, $sortby = 'asc') { if (is_array($list)) { $refer = $resultSet = array(); foreach ($list as $i => $data) { $refer[$i] = &$data[$field]; } switch ($sortby) { case 'asc': // 正向排序 asort($refer); break; case 'desc': // 逆向排序 arsort($refer); break; case 'nat': // 自然排序 natcasesort($refer); break; } foreach ($refer as $key => $val) { $resultSet[] = &$list[$key]; } return $resultSet; } return false; } // 駝峰命名法轉下劃線風格 function to_under_score($str) { $array = array(); for ($i = 0; $i < strlen($str); $i++) { if ($str[$i] == strtolower($str[$i])) { $array[] = $str[$i]; } else { if ($i > 0) { $array[] = '_'; } $array[] = strtolower($str[$i]); } } $result = implode('', $array); return $result; } /** * 自動生成新尺寸的圖片 * @param string $filename 檔名 * @param int $width 新圖片寬度 * @param int $height 新圖片高度(如果沒有填寫高度,把高度等比例縮小) * @param int $type 縮圖裁剪型別 * 1 => 等比例縮放型別 * 2 => 縮放後填充型別 * 3 => 居中裁剪型別 * 4 => 左上角裁剪型別 * 5 => 右下角裁剪型別 * 6 => 固定尺寸縮放型別 * @return string 生成縮圖的路徑 */ function resize($filename, $width, $height = null, $type = 1) { if (!is_file(ROOT_PATH . 'public/' . $filename)) { return; } // 如果沒有填寫高度,把高度等比例縮小 if ($height == null) { $info = getimagesize(ROOT_PATH . 'public/' . $filename); if ($width > $info[0]) { // 如果縮小後寬度尺寸大於原圖尺寸,使用原圖尺寸 $width = $info[0]; $height = $info[1]; } elseif ($width < $info[0]) { $height = floor($info[1] * ($width / $info[0])); } elseif ($width == $info[0]) { return $filename; } } $extension = pathinfo($filename, PATHINFO_EXTENSION); $old_image = $filename; $new_image = mb_substr($filename, 0, mb_strrpos($filename, '.')) . '_' . $width . 'x' . $height . '.' . $extension; $new_image = str_replace('image', 'cache', $new_image); // 縮圖存放於cache資料夾 if (!is_file(ROOT_PATH . 'public/' . $new_image) || filectime(ROOT_PATH . 'public/' . $old_image) > filectime(ROOT_PATH . 'public/' . $new_image)) { $path = ''; $directories = explode('/', dirname(str_replace('../', '', $new_image))); foreach ($directories as $directory) { $path = $path . '/' . $directory; if (!is_dir(ROOT_PATH . 'public/' . $path)) { @mkdir(ROOT_PATH . 'public/' . $path, 0777); } } list($width_orig, $height_orig) = getimagesize(ROOT_PATH . 'public/' . $old_image); if ($width_orig != $width || $height_orig != $height) { $image = \think\Image::open(ROOT_PATH . 'public/' . $old_image); switch ($type) { case 1: $image->thumb($width, $height, \think\Image::THUMB_SCALING); break; case 2: $image->thumb($width, $height, \think\Image::THUMB_FILLED); break; case 3: $image->thumb($width, $height, \think\Image::THUMB_CENTER); break; case 4: $image->thumb($width, $height, \think\Image::THUMB_NORTHWEST); break; case 5: $image->thumb($width, $height, \think\Image::THUMB_SOUTHEAST); break; case 5: $image->thumb($width, $height, \think\Image::THUMB_FIXED); break; default: $image->thumb($width, $height, \think\Image::THUMB_SCALING); break; } $image->save(ROOT_PATH . 'public/' . $new_image); } else { copy(ROOT_PATH . 'public/' . $old_image, ROOT_PATH . 'public/' . $new_image); } } return $new_image; } /** * hashids加密函式 * @param $id * @param string $salt * @param int $min_hash_length * @return bool|string * @throws Exception */ function hashids_encode($id, $salt = '', $min_hash_length = 6) { return (new Hashids\Hashids($salt, $min_hash_length))->encode($id); } /** * hashids解密函式 * @param $id * @param string $salt * @param int $min_hash_length * @return null * @throws Exception */ function hashids_decode($id, $salt = '', $min_hash_length = 6) { $id = (new Hashids\Hashids($salt, $min_hash_length))->decode($id); if (empty($id)) { return null; } return $id['0']; } /** * 記錄日誌 * 儲存後臺使用者行為 * @param string $remark 日誌備註 */ function insert_admin_log($remark) { if (session('?admin_auth')) { db('adminLog')->insert([ 'admin_id' => session('admin_auth.admin_id'), 'username' => session('admin_auth.username'), 'useragent' => request()->server('HTTP_USER_AGENT'), 'ip' => request()->ip(), 'url' => request()->url(true), 'method' => request()->method(), 'type' => request()->type(), 'param' => json_encode(request()->param()), 'remark' => $remark, 'create_time' => time(), ]); } } /** * 儲存前臺使用者行為 * @param string $remark 日誌備註 */ function insert_user_log($remark) { if (session('?user_auth')) { db('userLog')->insert([ 'user_id' => session('user_auth.user_id'), 'username' => session('user_auth.username'), 'useragent' => request()->server('HTTP_USER_AGENT'), 'ip' => request()->ip(), 'url' => request()->url(true), 'method' => request()->method(), 'type' => request()->type(), 'param' => json_encode(request()->param()), 'remark' => $remark, 'create_time' => time(), ]); } } /** * 檢測管理員是否登入 * @return integer 0/管理員ID */ function is_admin_login() { $admin = session('admin_auth'); if (empty($admin)) { return 0; } else { return session('admin_auth_sign') == data_auth_sign($admin) ? $admin['admin_id'] : 0; } } /** * 檢測會員是否登入 * @return integer 0/管理員ID */ function is_user_login() { $user = session('user_auth'); if (empty($user)) { return 0; } else { return session('user_auth_sign') == data_auth_sign($user) ? $user['user_id'] : 0; } } /** * 資料簽名認證 * @param array $data 被認證的資料 * @return string 簽名 */ function data_auth_sign($data) { // 資料型別檢測 if (!is_array($data)) { $data = (array)$data; } ksort($data); // 排序 $code = http_build_query($data); // url編碼並生成query字串 $sign = sha1($code); // 生成簽名 return $sign; } /** * 清除系統快取 * @param null $directory * @return bool */ function clear_cache($directory = null) { $directory = empty($directory) ? ROOT_PATH . 'runtime/cache/' : $directory; if (is_dir($directory) == false) { return false; } $handle = opendir($directory); while (($file = readdir($handle)) !== false) { if ($file != "." && $file != "..") { is_dir($directory . '/' . $file) ? clear_cache($directory . '/' . $file) : unlink($directory . '/' . $file); } } if (readdir($handle) == false) { closedir($handle); rmdir($directory); } }
2.TP中常用的JS歸納,基於layui
var layer = layui.layer, form = layui.form, element = layui.element, laydate = layui.laydate, upload = layui.upload, table = layui.table; // 通用提交 form.on('submit(*)', function (data) { var index = layer.msg('提交中,請稍候', { icon: 16, time: false, shade: 0.3 }); $(data.elem).attr('disabled', true); $.ajax({ url: data.form.action, type: data.form.method, dataType: 'json', data: $(data.form).serialize(), success: function (result) { if (result.code === 1 && result.url != '') { setTimeout(function () { location.href = result.url; }, 1000); } else { $(data.elem).attr('disabled', false); } layer.close(index); layer.msg(result.msg); }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); return false; }); // 父視窗通用提交 form.on('submit(i)', function (data) { var index = layer.msg('提交中,請稍候', { icon: 16, time: false, shade: 0.3 }); $.ajax({ url: data.form.action, type: data.form.method, dataType: 'json', data: $(data.form).serialize(), success: function (result) { if (result.code === 1) { setTimeout(function () { parent.location.reload(); }, 1000); } layer.close(index); layer.msg(result.msg); }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); return false; }); // 通用開關 form.on('switch(*)', function (data) { var index = layer.msg('修改中,請稍候', { icon: 16, time: false, shade: 0.3 }); // 引數 var obj = {}; obj[$(this).attr('name')] = this.checked == true ? 1 : 0; obj['_verify'] = 0; $.ajax({ url: $(this).data('url'), type: 'post', dataType: 'json', data: obj, success: function (result) { layer.close(index); layer.msg(result.msg); }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); }); // 通用全選 form.on('checkbox(*)', function (data) { $('.layui-table tbody input[lay-skin="primary"]').each(function (index, item) { item.checked = data.elem.checked; }); form.render('checkbox'); }); // 通用提交 $('.ajax-submit').on('click', function () { var than = $(this); var form = $(this).parents('form'); var index = layer.msg('提交中,請稍候', { icon: 16, time: false, shade: 0.3 }); than.attr('disabled', true); $.ajax({ url: form.attr('action'), type: form.attr('method'), dataType: 'json', data: $(data.form).serialize(), success: function (result) { if (result.code === 1 && result.url != '') { setTimeout(function () { location.href = result.url; }, 1000); } else { than.attr('disabled', false); } layer.close(index); layer.msg(result.msg); }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); return false; }); // 通用非同步 $('.ajax-action').on('click', function () { var url = $(this).attr('href'); var index = layer.msg('請求中,請稍候', { icon: 16, time: false, shade: 0.3 }); $.ajax({ url: url, type: 'post', dataType: 'json', success: function (result) { if (result.code === 1 && result.url != '') { setTimeout(function () { location.href = result.url; }, 1000); } layer.close(index); layer.msg(result.msg); }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); return false; }); // 通用更新 $('.ajax-update').on('blur', function () { // 引數 var obj = {}; obj[$(this).attr('name')] = $(this).val(); obj['_verify'] = 0; $.ajax({ url: $(this).data('url'), type: 'post', dataType: 'json', data: obj, success: function (result) { if (result.code === 1) { layer.msg(result.msg); setTimeout(function () { location.reload(); }, 1000); } }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); return false; }); // 通用刪除 $('.ajax-delete').on('click', function () { var url = $(this).attr('href'); layer.confirm('確定刪除?', { icon: 3, title: '提示' }, function (index) { var index = layer.msg('刪除中,請稍候', { icon: 16, time: false, shade: 0.3 }); $.ajax({ url: url, type: 'post', dataType: 'json', success: function (result) { console.log(result); if (result.code === 1 && result.url != '') { setTimeout(function () { location.href = result.url; }, 1000); } layer.close(index); layer.msg(result.msg); }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); }); return false; }); // 通用詳情 $('.ajax-detail').on('click', function () { var title = $(this).html(); var url = $(this).attr('href'); var index = layer.open({ title: title, type: 2, content: url, success: function (layero, index) { setTimeout(function () { layer.tips('點選此處返回', '.layui-layer-setwin .layui-layer-close', { tips: 3 }); }, 500) } }) layer.full(index); return false; }); // 通用視窗 $('.ajax-iframe').on('click', function () { var title = $(this).html(); var url = $(this).attr('href'); var width = $(this).data('width'); var height = $(this).data('height'); var index = layer.open({ title: title, type: 2, area: [width, height], content: url, }) return false; }); // 通用搜索 $('.ajax-search').on('click', function () { var form = $(this).parents('form'); var url = form.attr('action'); var query = form.serialize(); query = query.replace(/(&|^)(\w*?\d*?\-*?_*?)*?=?((?=&)|(?=$))/g, ''); query = query.replace(/^&/g, ''); if (url.indexOf('?') > 0) { url += '&' + query; } else { url += '?' + query; } location.href = url; return false; }); // 通用批量 $('.ajax-batch').on('click', function () { var url = $(this).attr('href'); var val = []; $('.layui-table tbody input[lay-skin="primary"]:checked').each(function (i) { val[i] = $(this).val(); }); if (val === undefined || val.length == 0) { layer.msg('請選擇資料'); return false; } var index = layer.msg('請求中,請稍候', { icon: 16, time: false, shade: 0.3 }); // 引數 var obj = {}; obj[$('.layui-table tbody input[lay-skin="primary"]:checked').attr('name')] = val; obj['_verify'] = 0; $.ajax({ url: url, type: 'post', dataType: 'json', data: obj, success: function (result) { if (result.code === 1 && result.url != '') { setTimeout(function () { location.reload(); }, 1000); } layer.close(index); layer.msg(result.msg); }, error: function (xhr, state, errorThrown) { layer.close(index); layer.msg(state + ':' + errorThrown); } }); return false; }); // 新增圖示 $('.ajax-icon').on('click', function () { var url = $(this).attr('href'); var index = layer.open({ title: '選擇圖示', type: 2, area: ['100%', '100%'], content: url }); return false; }); // 通用上傳 單圖 upload.render({ elem: '.ajax-images', url: '/admin/index/uploadImage', done: function (result) { // 上傳完畢回撥 if (result.code === 1) { this.item.siblings('.layui-input').val(result.url); this.item.parent().siblings().children(".layui-upload-img").attr('src',result.url); } else { layer.msg(result.msg); } } }); //通用上傳 檔案 upload.render({ elem: '.ajax-file', url: '/admin/index/uploadFile', accept: 'file', // 普通檔案 done: function (result) { // 上傳完畢回撥 if (result.code === 1) { this.item.siblings('.layui-input').val(result.url); } else { layer.msg(result.msg); } } }); upload.render({ elem: '.ajax-video', url: '/admin/index/uploadVideo', accept: 'video', // 視訊檔案 done: function (result) { // 上傳完畢回撥 if (result.code === 1) { this.item.siblings('.layui-input').val(result.url); } else { layer.msg(result.msg); } } }); // 通用相簿 多圖 upload.render({ elem: '.ajax-imgs', url: '/admin/index/uploadImage', multiple: true, done: function (result) { // 上傳完畢回撥 if (result.code === 1) { var html = '<div class="layui-form-item">' + '<label class="layui-form-label"></label><div class="layui-input-block"><input type="text" name="img[]" value="' + result.url + '" autocomplete="off" readonly class="layui-input">' + '<button type="button" class="layui-btn layui-btn-primary layui-btn-position delete-photo">' + '<i class="fa fa-times-circle"></i></button><img class="layui-upload-img" src="'+result.url+'" width="130px"></div></div>'; this.item.parents('.layui-form-item').after(html); } else { layer.msg(result.msg); } } }); // 刪除相簿 $('.layui-form').delegate('.delete-photo', 'click', function () { $(this).parents('.layui-form-item').remove(); }); // 選擇圖示 $('.iconlibs .fa').on('click', function () { $('input[name=icon]', window.parent.document).val($(this).attr('class')); parent.layer.closeAll(); }); form.verify({ username: function (value, item) { // value:表單的值、item:表單的DOM物件 if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) { return '使用者名稱不能有特殊字元'; } if (/(^\_)|(\__)|(\_+$)/.test(value)) { return '使用者名稱首尾不能出現下劃線\'_\''; } if (/^\d+\d+\d$/.test(value)) { return '使用者名稱不能全為數字'; } }, //我們既支援上述函式式的方式,也支援下述陣列的形式 //陣列的兩個值分別代表:[正則匹配、匹配不符時的提示文字] password: [ /^[\S]{6,12}$/ , '密碼必須6到12位,且不能出現空格' ] });