/**

Model 的数据校验
Ext.data.validations 本身的校验方法有 6 种(版本: 4.2.1)

email        - 电子信箱    - 验证一个电子邮件字符串是正确的格式
exclusion    - 排除        - 验证给定的值不存在于配置的 List 列表中。
format        - 格式        - 给定值通过正则表达式匹配,则返回true。
inclusion    - 包含        - 验证给定的值存在于配置的 List 列表中。
length        - 长度        - 如果给定的值是配置的最小值和最大值之间。
presence    - 存在        - 验证给定的值存在。

 */
// 定义一个 Pet 模型
Ext.define('Pet',{
    extend: 'Ext.data.Model',
    fields: [
        // User 的字段
        {name: 'id', type: 'int'},
        {name: 'email', type: 'string'},
        {name: 'name', type: 'string'},
        {name: 'nickname', type: 'string'},
        {name: 'gender', type: 'string'},
        {name: 'desc', type: 'string'}
    ],
    // 配置验证
    validations: [
        {type: 'email', field: 'email', message: '您输入的电子信箱格式格式错误!'},
        {type: 'exclusion', field: 'name', list:['pamisisi', 'alex']},
        {type: 'format', field: 'nickname', matcher: /^([\u4e00-\u9fa5]){2,4}$/, message: '您输入昵称必须为2-4个汉字!'},
        {type: 'inclusion', field: 'gender', list:['','']},
        {type: 'length', field: 'desc', min: 7, max: 20, message: '7-20个字符!'},
        {type: 'presence', field: 'id'}
    ]
});

Ext.onReady(function() {
    //创建 Pet 模型实例
    var pet  = Ext.create('Pet',{
        id: 1,
        email: 'pet.niuniu#live.com',
        name: 'niuniu',
        nickname: 'nif',
        gender: '',
        desc: '我家的狗狗!'
    });
    
    var errors = pet.validate();
    
    console.log("验证是否有效: " + errors.isValid());
    console.log("共有 " + errors.length + " 处错误!");
    
    errors.each(function(v){
        console.error(v.field + ': ' + v.message);
    });
});

 

 posted on 2013-12-04 16:17  AlexCK  阅读(670)  评论(0编辑  收藏  举报