博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
node.js学习笔记(27) node-orm进阶二
阅读量:6575 次
发布时间:2019-06-24

本文共 5608 字,大约阅读时间需要 18 分钟。

上一篇笔记学习了定义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 study27cd study27mkdir orm-validatecd orm-validatenpm initnpm installnpm install ormnpm install mysqltouch 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
第一次运行可以成功插入数据库:

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.

转载地址:http://yrmjo.baihongyu.com/

你可能感兴趣的文章
JSON for Modern C++ 3.6.0 发布
查看>>
好好讲一讲:到底什么是Java架构师(含福利放送,名额有限)
查看>>
网络爬虫随记:2018-03-12启(refreshing)
查看>>
Tomcat9.0部署iot.war(环境mysql8.0,centos7.2)
查看>>
Hanlp自然语言处理中的词典格式说明
查看>>
ASP.NETMVC Model验证(五)
查看>>
网络工程重要知识点
查看>>
如此IT,真是挨踢
查看>>
网络安全之iptables 实验篇一
查看>>
Spring3.0核心组件的源码简单分析
查看>>
如何成功清理重建CloudStack环境
查看>>
什么是Linq
查看>>
cacti 安装与配置
查看>>
EmEditor小功能与使用技巧
查看>>
VC6.0不支持标准库函数max和min
查看>>
添加WSS3.0中文模板
查看>>
shell脚本:监控MySQL服务是否正常
查看>>
Silverlight实用窍门系列:40.Silverlight中捕捉视频,截图保存到本地
查看>>
sudo报错案例-RHEL6
查看>>
“减少风险”还是“管理风险”哪一根才是救命稻草?
查看>>