project init

This commit is contained in:
zxy
2024-02-02 10:24:54 +08:00
commit 21a84c3035
253 changed files with 25212 additions and 0 deletions

204
untils/AxiosUtils.js Normal file
View File

@@ -0,0 +1,204 @@
import {
OpenLoading,
CloseLoading
} from "./Loading";
import {
BASE_URL,
AIRPORTS
} from "./Constants";
import website from "../config/website.js"
import {
Base64
} from 'js-base64'
import store from '@/store/';
import {
baseUrl
} from '@/config/env.js'
let showModal = true
/**
*
* @export
* @param {string} url
* @param {*} [data={}]
* @param {*} [config={}]
* @returns {Promise<any>}
*/
export function DoGet(url, data = {}, config = {}) {
return DoAjax({
url: url,
data,
method: "GET",
dataType: "json"
},
config
);
}
/**
*
* @export
* @param {string} url
* @param {*} [data={}]
* @param {*} [config={}]
* @returns {Promise<any>}
*/
export function DoPost(url, data = {}, config = {}) {
return DoAjax({
url: url,
data,
method: "POST",
dataType: "json"
},
config
);
}
export function request(options) {
const params = options.params
if (params) {
let query = ''
for (const key in params) {
if (params[key] !== undefined && params[key] !== null) {
query += `&${key}=${params[key]}`
}
}
query = '?' + query.substring(1)
options.url += query
}
return DoAjax(options)
}
async function DoAjax(options, config = {}) {
const func = Promisify(uni.request);
const header = options.headers || {};
header["Authorization"] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
const token = store.state.user.token;
if (token) {
header[website.tokenName] = "bearer " + token
}
if (baseUrl) {
options.url = baseUrl + options.url
}
options = Object.assign({}, options, {
header
});
let res = null
try {
res = (await func(options));
} catch (err) {
console.log({
err
})
res = err;
res.data = {}
} finally {}
// 获取状态码
const status = res.data.code || res.statusCode;
const statusWhiteList = website.statusWhiteList || [];
let message = res.data.msg || res.data.error_description || '未知错误';
//如果在白名单里则自行catch逻辑处理
if (statusWhiteList.includes(status)) throw res;
//如果是401则跳转到登录页面
if (status === 401) {
store.dispatch('FedLogOut').then(() => {
GoLogin()
});
throw new Error(message);
}
// 如果请求为非200否者默认统一处理
if (status !== 200) {
if (message === 'Bad credentials') {
message = '账号或密码错误'
}
uni.showToast({
title: message,
icon: 'none'
});
throw new Error(message);
}
return res;
}
/**
* 时间格式化
* @param {*} str
* @param {string} fmt
*/
export function DateFormat(str, fmt = "YYYY-MM-DD HH:mm:ss") {
return str ? moment(str).format(fmt) : "--";
}
/**
* 富文本添加域名
* @export
* @param {string} html
* @returns
*/
export function HtmlImgAddHost(html) {
return html.replace(
/ src="\//g,
` style="width:100% !important" src="${BASE_URL}/`
);
}
export function Promisify(func) {
return function(data) {
return new Promise((resolve, reject) => {
func({
...data,
success: resolve,
fail: reject
});
});
};
}
export function GoLogin() {
if (showModal) {
showModal = false
uni.showModal({
title: "提示",
content: "您还未登录,点击确认去登录",
success({
confirm
}) {
if (confirm) {
uni.redirectTo({
url: "/pages/login/login"
});
}
showModal = true
},
fail() {
showModal = true
}
})
}
}
/**
* 获取服务机场
* @export
* @param {string[]} list
*/
export function GetServiceIata(...list) {
const dic = new Set(AIRPORTS);
for (let i = 0; i < list.length; i++) {
if (dic.has(list[i])) return list[i];
}
return AIRPORTS[0];
}
export async function confirm(options) {
const func = Promisify(wx.showModal);
const res = await func(options);
if (res.confirm !== true) throw new Error(res.cancel);
}

5
untils/Constants.js Normal file
View File

@@ -0,0 +1,5 @@
export const BASE_URL = "https://weixin";

32
untils/Loading.js Normal file
View File

@@ -0,0 +1,32 @@
import { Subject } from "../lib/Rx";
const sub = new Subject();
let loading_count = 0;
export function OpenLoading() {
if (loading_count === 0)
wx.showLoading({
title: "正在加载...",
mask: true
});
loading_count++;
sub.next(loading_count);
}
export function CloseLoading() {
if (loading_count > 0) {
loading_count--;
}
// if (loading_count <= 0) wx.hideLoading();
sub.next(loading_count);
}
sub.debounceTime(500).subscribe(t => {
if (t === 0) {
wx.hideLoading();
}
});

1
untils/area.js Normal file

File diff suppressed because one or more lines are too long

40
untils/auth.js Normal file
View File

@@ -0,0 +1,40 @@
import {
getStore,
setStore
} from '@/untils/store.js'
export function getToken() {
return getStore({
name: 'token'
})
}
export function setToken(token) {
return setStore({
name: 'token',
content: token,
type: 'session'
})
}
export function getRefreshToken() {
return getStore({
name: 'refreshToken'
})
}
export function setRefreshToken(token) {
return setStore({
name: 'refreshToken',
content: token,
type: 'session'
})
}
export function removeToken() {
return setToken('')
}
export function removeRefreshToken() {
return setRefreshToken('')
}

69
untils/customized.js Normal file
View File

@@ -0,0 +1,69 @@
import {
setStore
} from '@/untils/store.js'
const hostDic = {
'xhwsd.jobslink.cn': {
name: '劳动力转移就业公共服务平台',
id: '773491043336192037'
},
'lihuayaoye.jobslink.cn': {
name: '河北利华药业有限公司',
id: '773491043327803404'
},
'shangchensuye.jobslink.cn': {
name: '河北尚辰塑业有限公司',
id: '773491043336192009'
},
'jinliu.jobslink.cn': {
name: '河北金柳化纤有限公司',
id: '773491043323609148'
},
'zhanlifangshui.jobslink.cn': {
name: '河北展利防水机械装备有限公司',
id: '773491043336192000'
},
'sjzjiecheng.jobslink.cn': {
name: '石家庄捷成门窗有限公司',
id: '773491043327803407'
},
'aoyinlaye.jobslink.cn': {
name: '奥垠行唐蜡业有限公司',
id: '773491043336192014'
},
'qytongfatielu.jobslink.cn': {
name: '河北同发铁路工程集团有限公司',
id: '773491043323609097'
},
'mmingda.jobslink.cn': {
name: '河北科创明达信息科技有限公司',
id: '773491043323609128'
},
'xibumahua.jobslink.cn': {
name: '西部马华',
id: '773491043327803395'
},
'kaixuanxinyue.jobslink.cn': {
name: '凯旋鑫悦',
id: '773491043331997734'
},
}
export function setPlatform($store, platformId, platformName) {
if (platformId) {
$store.commit('SET_HOME_NAV_SHOW', false);
$store.commit('SET_HOME_TITLE', platformName);
setStore({
name: 'platformId',
content: platformId
})
}
}
export function setPlatformByHostName($store) {
const hostname = window.location.hostname
if (hostDic.hasOwnProperty(hostname)) {
const dic = hostDic[hostname]
setPlatform($store, dic.id, dic.name)
}
}

51
untils/date.js Normal file
View File

@@ -0,0 +1,51 @@
export const calcDate = (date1, date2) => {
let date3 = date2 - date1;
let days = Math.floor(date3 / (24 * 3600 * 1000))
let leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
let hours = Math.floor(leave1 / (3600 * 1000))
let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
let minutes = Math.floor(leave2 / (60 * 1000))
let leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
let seconds = Math.round(date3 / 1000)
return {
leave1,
leave2,
leave3,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds,
}
}
/**
* 日期格式化
*/
export function dateFormat(date, format) {
format = format || 'yyyy-MM-dd hh:mm:ss';
if (date !== 'Invalid Date') {
let o = {
"M+": date.getMonth() + 1, //month
"d+": date.getDate(), //day
"h+": date.getHours(), //hour
"m+": date.getMinutes(), //minute
"s+": date.getSeconds(), //second
"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
"S": date.getMilliseconds() //millisecond
}
if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (let k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length === 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
return format;
}
return '';
}

107
untils/filters.wxs Normal file
View File

@@ -0,0 +1,107 @@
// <wxs module="filters" src="../../utils/filters.wxs"></wxs>
var BASE_URL = "https://api.vip.shairport.com/weixin";
/**
* filters.ImgUrl(item.BANNER)
* @param str
*/
var ImgUrl = function(str) {
if (!str || str.indexOf("/") !== 0) return str;
return BASE_URL + str;
};
/**
* padStart
* @param {number} string
* @param {number} length
* @param {string} pad
* @returns
*/
function padStart(string, length, pad) {
var s = string.toString();
if (!s || s.length >= length) return string;
var len = length - s.length;
var result = "";
for (var i = 0; i < len; i++) {
result += pad;
}
return result + string;
}
/**
* filters.DateTime(item.CREATETIME, "YYYY-MM-DD")
* @param dateStr
* @param formatStr
*/
var DateTime = function(dateStr, formatStr) {
if (!dateStr) return dateStr;
var date = getDate(dateStr);
var my_y = date.getFullYear().toString();
var my_M = date.getMonth();
var my_D = date.getDate();
var my_H = date.getHours();
var my_m = date.getMinutes();
var my_s = date.getSeconds();
var matches = {
YY: my_y.slice(-2),
YYYY: my_y,
M: my_M + 1,
MM: padStart(my_M + 1, 2, "0"),
D: my_D,
DD: padStart(my_D, 2, "0"),
H: my_H.toString(),
HH: padStart(my_H, 2, "0"),
m: my_m.toString(),
mm: padStart(my_m, 2, "0"),
s: my_s.toString(),
ss: padStart(my_s, 2, "0")
};
var keys = [
"YYYY",
"YY",
"MM",
"M",
"DD",
"D",
"HH",
"H",
"mm",
"m",
"ss",
"s"
];
var str = formatStr || "YYYY-MM-DD HH:mm:ss";
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
while (str.indexOf(key) !== -1) {
str = str.replace(key, matches[key]);
}
}
return str;
// var REGEX_FORMAT = getRegExp(
// "Y{2,4}|M{1,4}|D{1,2}|H{1,2}|m{1,2}|s{1,2}",
// "g"
// );
// return str.replace(REGEX_FORMAT, function(match, str1) {
// return str1 || matches[match];
// });
};
module.exports = {
ImgUrl: ImgUrl,
DateTime: DateTime
};

96
untils/format.js Normal file
View File

@@ -0,0 +1,96 @@
import Decimal from 'decimal.js'
/**
* 格式化金额格式
* 返回的是字符串23,245.12保留2位小数
* @param num
* @returns {string}
*/
export function toMoney(num) {
num = num.toFixed(2)
num = parseFloat(num)
num = num.toLocaleString('zh', {
minimumFractionDigits: 2,
useGrouping: true
})
return num
}
/**
* 格式化金额格式
* 返回的是字符串23,245.12保留2位小数
* @param num
* @returns {string}
*/
export function toDoller(val) {
return new Decimal(val).div(100).toNumber();
}
/**
* 格式化金额格式
* 返回的是字符串23,245.12保留2位小数
* @param num
* @returns {string}
*/
export function toCent(val) {
return new Decimal(val).mul(100).toNumber();
}
export function moneyFormat(val) {
return toMoney(toDoller(val));
}
/**
* 日期格式化
*/
/**
* 日期格式化
*/
export function dateFormat(date, format = 'yyyy-MM-dd') {
if(typeof(date) === 'string'){
date = date.replace(/\-/g, "/")
}
format = format || 'yyyy-MM-dd hh:mm:ss';
date = new Date(date);
if (date !== 'Invalid Date') {
let o = {
"M+": date.getMonth() + 1, //month
"d+": date.getDate(), //day
"h+": date.getHours(), //hour
"m+": date.getMinutes(), //minute
"s+": date.getSeconds(), //second
"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
"S": date.getMilliseconds() //millisecond
}
if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (let k in o)
if (new RegExp("(" + k + ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length === 1 ? o[k] :
("00" + o[k]).substr(("" + o[k]).length));
return format;
}
return '';
}
export function phoneFilter(val) {
return val.substring(0, 3) + '****' + val.substring(7)
}
export function idNumberFilter(val) {
return val.substring(0, 3) + '************' + val.substring(14)
}
export function bankCardFilter(val) {
return val.substring(0, 4) + ' **** **** ' + val.substring(val.length - 4)
}
export function moneyComdify(val){
var n = (val/100).toFixed(2);
var re = /\d{1,3}(?=(\d{3})+$)/g;
var num = n.replace(/^(\d+)((\.\d+)?)$/,function(s,s1,s2){return s1.replace(re,"$&,")+s2;});
return num;
}

22
untils/func.js Normal file
View File

@@ -0,0 +1,22 @@
const windowWidth = uni.getSystemInfoSync().windowWidth
class func {
/**
* rpx转换为px
* @param rpx
* @returns {number}
*/
static rpxTopx(rpx) {
return (windowWidth / 750) * rpx;
}
}
/**
* 通用工具类
*/
export default {
install(Vue, options) {
// 4. 添加实例方法
Vue.prototype.$util = func
}
}

352
untils/html-parser.js Normal file
View File

@@ -0,0 +1,352 @@
/*
* HTML5 Parser By Sam Blowes
*
* Designed for HTML5 documents
*
* Original code by John Resig (ejohn.org)
* http://ejohn.org/blog/pure-javascript-html-parser/
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* ----------------------------------------------------------------------------
* License
* ----------------------------------------------------------------------------
*
* This code is triple licensed using Apache Software License 2.0,
* Mozilla Public License or GNU Public License
*
* ////////////////////////////////////////////////////////////////////////////
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* ////////////////////////////////////////////////////////////////////////////
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is Simple HTML Parser.
*
* The Initial Developer of the Original Code is Erik Arvidsson.
* Portions created by Erik Arvidssson are Copyright (C) 2004. All Rights
* Reserved.
*
* ////////////////////////////////////////////////////////////////////////////
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* ----------------------------------------------------------------------------
* Usage
* ----------------------------------------------------------------------------
*
* // Use like so:
* HTMLParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* // or to get an XML string:
* HTMLtoXML(htmlString);
*
* // or to get an XML DOM Document
* HTMLtoDOM(htmlString);
*
* // or to inject into an existing document/DOM node
* HTMLtoDOM(htmlString, document);
* HTMLtoDOM(htmlString, document.body);
*
*/
// Regular Expressions for parsing tags and attributes
var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;
var endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/;
var attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; // Empty Elements - HTML 5
var empty = makeMap('area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr'); // Block Elements - HTML 5
// fixed by xxx 将 ins 标签从块级名单中移除
var block = makeMap('a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video'); // Inline Elements - HTML 5
var inline = makeMap('abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'); // Elements that you can, intentionally, leave open
// (and which close themselves)
var closeSelf = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'); // Attributes that have their values filled in disabled="disabled"
var fillAttrs = makeMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'); // Special Elements (can contain anything)
var special = makeMap('script,style');
function HTMLParser(html, handler) {
var index;
var chars;
var match;
var stack = [];
var last = html;
stack.last = function () {
return this[this.length - 1];
};
while (html) {
chars = true; // Make sure we're not in a script or style element
if (!stack.last() || !special[stack.last()]) {
// Comment
if (html.indexOf('<!--') == 0) {
index = html.indexOf('-->');
if (index >= 0) {
if (handler.comment) {
handler.comment(html.substring(4, index));
}
html = html.substring(index + 3);
chars = false;
} // end tag
} else if (html.indexOf('</') == 0) {
match = html.match(endTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(endTag, parseEndTag);
chars = false;
} // start tag
} else if (html.indexOf('<') == 0) {
match = html.match(startTag);
if (match) {
html = html.substring(match[0].length);
match[0].replace(startTag, parseStartTag);
chars = false;
}
}
if (chars) {
index = html.indexOf('<');
var text = index < 0 ? html : html.substring(0, index);
html = index < 0 ? '' : html.substring(index);
if (handler.chars) {
handler.chars(text);
}
}
} else {
html = html.replace(new RegExp('([\\s\\S]*?)<\/' + stack.last() + '[^>]*>'), function (all, text) {
text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, '$1$2');
if (handler.chars) {
handler.chars(text);
}
return '';
});
parseEndTag('', stack.last());
}
if (html == last) {
throw 'Parse Error: ' + html;
}
last = html;
} // Clean up any remaining tags
parseEndTag();
function parseStartTag(tag, tagName, rest, unary) {
tagName = tagName.toLowerCase();
if (block[tagName]) {
while (stack.last() && inline[stack.last()]) {
parseEndTag('', stack.last());
}
}
if (closeSelf[tagName] && stack.last() == tagName) {
parseEndTag('', tagName);
}
unary = empty[tagName] || !!unary;
if (!unary) {
stack.push(tagName);
}
if (handler.start) {
var attrs = [];
rest.replace(attr, function (match, name) {
var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : fillAttrs[name] ? name : '';
attrs.push({
name: name,
value: value,
escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') // "
});
});
if (handler.start) {
handler.start(tagName, attrs, unary);
}
}
}
function parseEndTag(tag, tagName) {
// If no tag name is provided, clean shop
if (!tagName) {
var pos = 0;
} // Find the closest opened tag of the same type
else {
for (var pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos] == tagName) {
break;
}
}
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (handler.end) {
handler.end(stack[i]);
}
} // Remove the open elements from the stack
stack.length = pos;
}
}
}
function makeMap(str) {
var obj = {};
var items = str.split(',');
for (var i = 0; i < items.length; i++) {
obj[items[i]] = true;
}
return obj;
}
function removeDOCTYPE(html) {
return html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
}
function parseAttrs(attrs) {
return attrs.reduce(function (pre, attr) {
var value = attr.value;
var name = attr.name;
if (pre[name]) {
pre[name] = pre[name] + " " + value;
} else {
pre[name] = value;
}
return pre;
}, {});
}
function parseHtml(html) {
html = removeDOCTYPE(html);
var stacks = [];
var results = {
node: 'root',
children: []
};
HTMLParser(html, {
start: function start(tag, attrs, unary) {
var node = {
name: tag
};
if (attrs.length !== 0) {
node.attrs = parseAttrs(attrs);
}
if (unary) {
var parent = stacks[0] || results;
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
} else {
stacks.unshift(node);
}
},
end: function end(tag) {
var node = stacks.shift();
if (node.name !== tag) console.error('invalid state: mismatch end tag');
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
chars: function chars(text) {
var node = {
type: 'text',
text: text
};
if (stacks.length === 0) {
results.children.push(node);
} else {
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
},
comment: function comment(text) {
var node = {
node: 'comment',
text: text
};
var parent = stacks[0];
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
});
return results.children;
}
export default parseHtml;

33
untils/store.js Normal file
View File

@@ -0,0 +1,33 @@
import website from '@/config/website'
const keyName = website.key + '-';
export const getStore = (params = {}) => {
let {
name,
debug
} = params;
name = keyName + name
const obj = uni.getStorageSync(name)
if (debug) {
return obj;
}
return obj.content
}
export const setStore = (params = {}) => {
let {
name,
content,
type,
} = params;
name = keyName + name
let obj = {
dataType: typeof(content),
content: content,
type: type,
datetime: new Date().getTime()
}
return uni.setStorageSync(name, obj)
}

33
untils/uniModal.js Normal file
View File

@@ -0,0 +1,33 @@
let showModal = true
export function showUniModal(modalTitle, content, whetherCancel, confirmText, pageUrl, cancelUrl) {
if (showModal) {
showModal = false;
uni.showModal({
id: 'testModal',
title: modalTitle,
content: content,
showCancel: whetherCancel,
confirmText: confirmText,
success({
confirm
}) {
if (confirm) {
uni.navigateTo({
url: pageUrl
});
} else {
if (cancelUrl != '') {
uni.switchTab({
url: cancelUrl
})
}
}
showModal = true
},
fail() {
showModal = true
}
});
}
}

393
untils/validate.js Normal file
View File

@@ -0,0 +1,393 @@
/**
* Created by jiachenpan on 16/11/18.
*/
export function isvalidUsername(str) {
const valid_map = ['admin', 'editor']
return valid_map.indexOf(str.trim()) >= 0
}
/* 合法uri*/
export function validateURL(textval) {
const urlregex =
/^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
return urlregex.test(textval)
}
/**
* 邮箱
* @param {*} s
*/
export function isEmail(s) {
return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
/**
* 手机号码
* @param {*} s
*/
export function isMobile(s) {
return /^1[0-9]{10}$/.test(s)
}
/**
* 电话号码
* @param {*} s
*/
export function isPhone(s) {
return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}
/**
* URL地址
* @param {*} s
*/
export function isURL(s) {
return /^http[s]?:\/\/.*/.test(s)
}
/* 小写字母*/
export function validateLowerCase(str) {
const reg = /^[a-z]+$/
return reg.test(str)
}
/* 大写字母*/
export function validateUpperCase(str) {
const reg = /^[A-Z]+$/
return reg.test(str)
}
/* 大小写字母*/
export function validatAlphabets(str) {
const reg = /^[A-Za-z]+$/
return reg.test(str)
}
/*验证pad还是pc*/
export const vaildatePc = function() {
const userAgentInfo = navigator.userAgent;
const Agents = ["Android", "iPhone",
"SymbianOS", "Windows Phone",
"iPad", "iPod"
];
let flag = true;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false;
break;
}
}
return flag;
}
/**
* validate email
* @param email
* @returns {boolean}
*/
export function validateEmail(email) {
const re =
/^(([^<>()\\[\]\\.,;:\s@"]+(\.[^<>()\\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email)
}
/**
* 判断身份证号码
*/
export function cardid(code) {
let list = [];
let result = true;
let msg = '';
var city = {
11: "北京",
12: "天津",
13: "河北",
14: "山西",
15: "内蒙古",
21: "辽宁",
22: "吉林",
23: "黑龙江 ",
31: "上海",
32: "江苏",
33: "浙江",
34: "安徽",
35: "福建",
36: "江西",
37: "山东",
41: "河南",
42: "湖北 ",
43: "湖南",
44: "广东",
45: "广西",
46: "海南",
50: "重庆",
51: "四川",
52: "贵州",
53: "云南",
54: "西藏 ",
61: "陕西",
62: "甘肃",
63: "青海",
64: "宁夏",
65: "新疆",
71: "台湾",
81: "香港",
82: "澳门",
91: "国外 "
};
if (!validatenull(code)) {
if (code.length == 18) {
if (!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
msg = "证件号码格式错误";
} else if (!city[code.substr(0, 2)]) {
msg = "地址编码错误";
} else {
//18位身份证需要验证最后一位校验位
code = code.split('');
//∑(ai×Wi)(mod 11)
//加权因子
var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
//校验位
var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x'];
var sum = 0;
var ai = 0;
var wi = 0;
for (var i = 0; i < 17; i++) {
ai = code[i];
wi = factor[i];
sum += ai * wi;
}
if (parity[sum % 11] != code[17]) {
msg = "证件号码校验位错误";
} else {
result = false;
}
}
} else {
msg = "证件号码长度不为18位";
}
} else {
msg = "证件号码不能为空";
}
list.push(result);
list.push(msg);
return list;
}
/**
* 判断手机号码是否正确
*/
export function isvalidatemobile(phone) {
let list = [];
let result = true;
let msg = '';
var isPhone = new RegExp('^0\d{2,3}-?\d{7,8}$');
//增加134 减少|1349[0-9]{7}增加181,增加145增加17[678]
if (!validatenull(phone)) {
if (phone.length == 11) {
if (isPhone.test(phone)) {
msg = '手机号码格式不正确';
} else {
result = false;
}
} else {
msg = '手机号码长度不为11位';
}
} else {
msg = '手机号码不能为空';
}
list.push(result);
list.push(msg);
return list;
}
/**
* 判断姓名是否正确
*/
export function validatename(name) {
var regName = /^[\u4e00-\u9fa5]{2,4}$/;
if (!regName.test(name)) return false;
return true;
}
/**
* 判断是否为整数
*/
export function validatenumber(num) {
return typeof(num) === 'number';
}
/**
* 判断是否为整数
*/
export function validatenum(num, type) {
let regName = /[^\d.]/g;
if (type == 1) {
if (!regName.test(num)) return false;
} else if (type == 2) {
regName = /[^\d]/g;
if (!regName.test(num)) return false;
}
return true;
}
/**
* 判断是否为小数
*/
export function validatenumord(num, type) {
let regName = /[^\d.]/g;
if (type == 1) {
if (!regName.test(num)) return false;
} else if (type == 2) {
regName = /[^\d.]/g;
if (!regName.test(num)) return false;
}
return true;
}
/**
* 判断是否为空
*/
export function validatenull(val) {
if (typeof val == 'boolean') {
return false;
}
if (typeof val == 'number') {
return false;
}
if (val instanceof Array) {
if (val.length == 0) return true;
} else if (val instanceof Object) {
if (JSON.stringify(val) === '{}') return true;
} else {
if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
return false;
}
return false;
}
/*判断身份证*/
// 每位加权因子
var powers = ['7', '9', '10', '5', '8', '4', '2', '1', '6', '3', '7', '9', '10', '5', '8', '4', '2']
// 第18位校检码
var parityBit = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
var provinceAndCitys = {
11: '北京',
12: '天津',
13: '河北',
14: '山西',
15: '内蒙古',
21: '辽宁',
22: '吉林',
23: '黑龙江',
31: '上海',
32: '江苏',
33: '浙江',
34: '安徽',
35: '福建',
36: '江西',
37: '山东',
41: '河南',
42: '湖北',
43: '湖南',
44: '广东',
45: '广西',
46: '海南',
50: '重庆',
51: '四川',
52: '贵州',
53: '云南',
54: '西藏',
61: '陕西',
62: '甘肃',
63: '青海',
64: '宁夏',
65: '新疆',
71: '台湾',
81: '香港',
82: '澳门',
91: '国外'
}
// 校验18位的身份证号码
export function check18IdCardNo(idCardNo) {
// 18位身份证号码的基本格式校验
var check = /^[1-9]\d{5}[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))\d{3}(\d|x|X)$/.test(idCardNo)
if (!check) return false
// 校验地址码
var addressCode = idCardNo.substring(0, 6)
check = checkAddressCode(addressCode)
if (!check) return false
// 校验日期码
var birDayCode = idCardNo.substring(6, 14)
check = checkBirthDayCode(birDayCode)
if (!check) return false
// 验证校检码
return checkParityBit(idCardNo)
}
// 校验地址码
function checkAddressCode(addressCode) {
var check = /^[1-9]\d{5}$/.test(addressCode)
if (!check) return false
if (provinceAndCitys[parseInt(addressCode.substring(0, 2))]) {
return true
} else {
return false
}
}
// 校验日期码
function checkBirthDayCode(birDayCode) {
var check = /^[1-9]\d{3}((0[1-9])|(1[0-2]))((0[1-9])|([1-2][0-9])|(3[0-1]))$/.test(birDayCode)
if (!check) return false
var yyyy = parseInt(birDayCode.substring(0, 4), 10)
var mm = parseInt(birDayCode.substring(4, 6), 10)
var dd = parseInt(birDayCode.substring(6), 10)
var xdata = new Date(yyyy, mm - 1, dd)
if (xdata > new Date()) {
return false
} else if ((xdata.getFullYear() === yyyy) && (xdata.getMonth() === mm - 1) && (xdata.getDate() === dd)) {
return true
} else {
return false
}
}
// 验证校检码
function checkParityBit(idCardNo) {
var parityBit = idCardNo.charAt(17).toUpperCase()
if (getParityBit(idCardNo) === parityBit) {
return true
} else {
return false
}
}
// 计算校检码
function getParityBit(idCardNo) {
var id17 = idCardNo.substring(0, 17)
// 加权
var power = 0
for (let i = 0; i < 17; i++) {
power += parseInt(id17.charAt(i), 10) * parseInt(powers[i])
}
// 取模
var mod = power % 11
return parityBit[mod]
}
// 验证excel文件格式
export function isExcel(file) {
const isXlsx =
file.type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
file.type === "application/vnd.ms-excel" ||
file.type === "application/x-excel" ||
file.name.indexOf("xls") > -1 ||
file.name.indexOf("xlsx") > -1;
return isXlsx;
}
// 验证密码
export function password(psw) {
var reg = new RegExp('^.{6,20}$');
return !reg.test(psw);
}