主题特性

  1. 简单,js 配置 className,css 定义主题样式
  2. 独立,不同表单可以应用不同主题
  3. 自由,除了主题参数,其他参数也都可以配置到主题中
  4. 灵活,主题配置本质上是在传参,优先级高于全局配置,但是又会被调用时的传参覆盖

配置主题

(1). 调用 $.validator.setTheme() 接口

$.validator.setTheme("themeName", {
    formClass: "nice-flat",
    msgClass: "n-right"
});

其中的 formClass 参数定义了 CSS 的名称空间,表单初始化后自动添加到 form 上面。msgClass 参数定义了每条消息拥有的 CSS 类。虽然这两个参数没有要求,但是建议 msgClass 按照以下 4 个类名命名:

  1. n-top:使消息显示在输入框上边
  2. n-right:使消息显示在输入框右边
  3. n-bottom:使消息显示在输入框下边
  4. n-left:使消息显示在输入框左边

nice-validator 对 msgClass 有一个方向的检测机制,包含 top|right|bottom|left 的名称可以控制消息插入的位置。

(2). 配置更多参数

  1. 每个主题可以配置所有参数,互不干扰
  2. 配置优先级:data-validator-option > options > theme options > global options

编写主题样式

主题 CSS 样式可以写在 jquery.validator.css 文件中,也可以定义在你的其他样式表中。

官方的主题样式使用 stylus 工具开发,所有主题配置文件放置在 src/themes 目录,然后通过src/jquery.validator.styl 文件导入,编译该文件就得到 dist 目录下的 jquery.validator.css 文件。

以下是 simple 系列主题代码:

// local/zh-Cn.js 中的配置
$.validator.setTheme({
    'simple_right': {
        formClass: 'n-simple',
        msgClass: 'n-right'
    },
    'simple_bottom': {
        formClass: 'n-simple',
        msgClass: 'n-bottom'
    }
});
/* src/themes/simple.styl */
.n-simple {
    .msg-wrap {
        position: absolute;
        z-index: 1;
        .n-icon {
            background-image: url(images/validator_simple.png);
        }
    }
    .n-top {
        .msg-wrap {
            bottom: 100%;
        }
    }
    .n-bottom {
        .msg-wrap {
            top: 100%;
        }
    }
    .n-left, .n-right {
        margin-top: 5px;
    }
    .n-bottom .msg-wrap {
        margin-top: 3px;
    }
    .n-tip {
        .n-icon {display:none;}
    }
}

自定义消息结构

参见 msgMaker 参数