validate.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const strategies = {
  2. // errorMsg参数,提升了适用性
  3. isNoEmpty: function (value, errorMsg) { //不为空
  4. if (value === '' || value === undefined || value === false || JSON.stringify(value) === '[]' || JSON.stringify(value) === '{}') {
  5. // 返回字符串true 错误信息
  6. return errorMsg;
  7. }
  8. },
  9. minLength: function (value, length, errorMsg) { //限制最小长度
  10. if (value.length < length) {
  11. return errorMsg;
  12. }
  13. },
  14. maxLength: function (value, length, errorMsg) { //限制最小长度
  15. if (value.length > length) {
  16. return errorMsg;
  17. }
  18. },
  19. isMobile: function (value, errorMsg) {
  20. if (!/^([0-9]{11})$/.test(value)) { //电话号码校验
  21. return errorMsg;
  22. }
  23. },
  24. isWx: function (value, errorMsg) {
  25. if (!/^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/.test(value)) { //微信码校验
  26. return errorMsg;
  27. }
  28. },
  29. isEmail: function (value, errorMsg) {
  30. if (!/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(value)) { //邮箱校验
  31. return errorMsg;
  32. }
  33. },
  34. money: function (value, errorMsg) {
  35. if (!/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value) || parseFloat(value) < 0.01) { //金额校验
  36. return errorMsg;
  37. }
  38. },
  39. name: function (value, errorMsg) {
  40. if (!/^[u4e00-u9fa5·0-9A-z]+$/.test(value)) { //金额校验
  41. return errorMsg;
  42. }
  43. },
  44. isUrl:function(value,errorMsg){
  45. if(value.indexOf('http') < 0){
  46. return errorMsg;
  47. }
  48. },
  49. // isUrl(value, errorMsg) {
  50. // if (!/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(value)) {
  51. // return errorMsg;
  52. // }
  53. // }
  54. };
  55. class Validate {
  56. constructor() {
  57. this.cache = []
  58. }
  59. }
  60. Validate.prototype.add = function (value, rule, errorMsg) {
  61. this.cache.push(function () {
  62. // 规则
  63. let method, arr;
  64. //判断为已有的策略还是新增的
  65. if (typeof rule === 'string') {
  66. arr = rule.split(':');
  67. let strategy = arr.shift();
  68. method = strategies[strategy];
  69. } else {
  70. arr = [];
  71. method = rule;
  72. }
  73. arr.unshift(value);
  74. arr.push(errorMsg);
  75. return method.apply(null, arr);
  76. });
  77. };
  78. Validate.prototype.start = function () {
  79. for (let i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
  80. let msg = validatorFunc();
  81. if (msg) {
  82. return msg;
  83. }
  84. }
  85. };
  86. export default Validate