node.js学习笔记(27) node-orm进阶二

上一篇笔记学习了定义Model的两种方法和Model的properties,用到了unique、size等几个常用的option。这些option除了对数据库定义的描述外,还有validate的作用。

当然node-orm还为我们提供了更加详细的validate功能。


Validations


orm.enforce是node-orm的一个子模块,专门用于validate。也许以前还有一个orm.validators模块,官方文档建议使用orm.enforce,既然我们以前没有用过orm.validators,那么直接忽略它的存在吧。

尝试一下orm.enforce如何使用吧。

创建新的项目orm-validate,并继续使用之间创建的nodejs数据库和user表:

mkdir study27
cd study27
mkdir orm-validate
cd orm-validate
npm init
npm install
npm install orm
npm install mysql
touch index.js


index.js:

var orm = require("orm");

orm.connect('mysql://root:root@localhost:3306/nodejs', function(err, db){
    if (err) throw err;
    var User = db.define("user", {
        id          :{type:'serial', mapsTo:'id', unique:true, size:11},
        name        :{type:'text', mapsTo:'name'},
        username    :{type:'text', mapsTo:'username'},
        password    :{type:'text', mapsTo:'password'},
        birthday    :{type:'date', mapsTo:'birthday', time:true}
    },{
        validations:{
            username:orm.enforce.unique('The username is already existed.')
        }
    });

    var user = new User(
        {
            name:'aaa',
            username:'aaa',
            password:'',
            birthday:'2010-10-10 10:10:10'
        }
    );
    user.save(function(err){
        if(err){
            console.log(err);
        }
    });
    User.find({}, function(err, items) {
        //console.log(items.length);
        for(var i=0;i<items.length;i++){
            console.log(JSON.stringify(items[i]));
        }
    });
});

第一次运行可以成功插入数据库:

lee@mypc ~/works/nodejs/study27/orm-validate $ node index.js 
{"id":1,"name":"lee","username":"admin","password":"admin","birthday":"1988-08-07T23:08:08.000Z"}
{"id":3,"name":"aaa","username":"aaa","password":"","birthday":"2010-10-10T02:10:10.000Z"}


当第二次运行的时候,数据库中已经存在username='aaa'的记录,就无法再次插入了:

lee@mypc ~/works/nodejs/study27/orm-validate $ node index.js 
{ [Error: The username is already existed.]
  property: 'username',
  value: 'aaa',
  msg: 'The username is already existed.',
  type: 'validation' }
{"id":1,"name":"lee","username":"admin","password":"admin","birthday":"1988-08-07T23:08:08.000Z"}
{"id":3,"name":"aaa","username":"aaa","password":"","birthday":"2010-10-10T02:10:10.000Z"}

每个property可以定义一个或一组(数组)validation。

orm.enforce定义了丰富的validators:

  • Required


enforce.required([ msg ])


Checks if a property is not null and not undefined. If can be false, 0 or "".


  • Empty string


enforce.notEmptyString([ msg ])


Checks if a property length is not zero. It can actually work with Arrays.


  • Same as


enforce.sameAs(property, [ msg ])


Checks if a property has the same (strict) value as another one. This is usefull for testing password matching.

  • Lists


    • Inside a list


enforce.lists.inside(list[, msg ])


Checks if the property is inside a list of items.


    • Outside a list


enforce.lists.outside(list[, msg ])


Checks if the property is not inside a list of items.


  • Ranges


    • In a number range


enforce.ranges.number(min[, max[, msg ]])


Checks if a value is inside a specific range of numbers. Either min or max can be set to undefined meaning that range side is Infinity.


Please note that this does not check for the type of value passed, you can even use this with Date objects.


    • In a length range


enforce.ranges.length(min[, max[, msg ]])


Does the same as the above but for the length property.


  • Security


    • Username


enforce.security.username([[ opts, ]msg ])


Checks if a value matches a username format. opts is also optional and is an object with the following keys:


length: the minimal length of the username (default = 2)

expr: the regular expression to be used to match a valid username (if not passed, it's built based on the minimal length)


    • Password


enforce.security.password([[ checks, ]msg ])


Checks if a value has some types of characters and a minimal length. checks has a default string luns6 which means:


l: lowercase letters

u: uppercase letters

n: numbers

s: special characters

6: minimal length of 6

You can of course change this to "lu4" (lowercase, uppercase, minimal length of 4). Please note that if you pass only one argument to this validator, it will assume it's the msg argument. If you want to change the default checks, you have to pass both arguments.


    • Credit Card


enforce.security.creditcard([[ types, ] msg ])


Checks if a value is a valid credit card number. It supports amex (American Express), visa, maestro, discover and mastercard. You can change the list of supported cards (types) by passing a list with only some of them. You can also pass luhn which will ignore card prefixes and lenght and only pass the number using the Luhn algorithm.


  • Patterns


    • Match


enforce.patterns.match(pattern, modifiers[, msg ])


Checks if property passes a specific regular expression. You can pass the pattern as a RegExp object (setting modifiers as null) or just pass a regular expression and it will be converted.


    • Hex string


enforce.patterns.hexString([ msg ])


Checks if a property matches a predefined RegExp object accepting insensitive hexadecimal characters.


    • E-mail


enforce.patterns.email([ msg ])


Checks if a property matches a predefined RegExp object accepting valid e-mail addresses.


    • IPv4


enforce.patterns.ipv4([ msg ])


Checks if a property matches a predefined RegExp object accepting valid IPv4 address.


    • IPv6


enforce.patterns.ipv6([ msg ])


Checks if a property matches a predefined RegExp object accepting valid IPv6 address.


    • MAC


enforce.patterns.mac([ msg ])


Checks if a property matches a predefined RegExp object accepting valid MAC address.


    • UUID v3


enforce.patterns.uuid3([ msg ])


Checks if a property matches a predefined RegExp object accepting valid UUID version 3.


    • UUID v4


enforce.patterns.uuid4([ msg ])


Checks if a property matches a predefined RegExp object accepting valid UUID version 4.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值