@Pattern,JSR303 bean验证:正则表达式检查最多5个单词,而不是空白(@Pattern , JSR303 bean validation : regex check max 5 words and not blank)
我在spring-mvc托管bean中使用JSR303 bean验证注释来验证文本输入。 我需要检查
- 如果一个字符串包含最多5个单词(这里的单词是字母或字母数字字符串),并且该字符串不能为空(一个空格)
我尝试这个:(仅仅匹配5个字)
@Pattern(message="max 5 words please" , regexp="^[a-zA-Z+#\-.0-9]{1,5}(\s[a-zA-Z+#\-.0-9]{1,5}){0,4}$") String keywords;
但我的Eclipse IDE说:无效的转义序列(有效的转义序列是\ b \ t \ n \ f \ r \“\'\)
I use JSR303 bean validation annotations in my spring-mvc managed bean to validate text input. I need to check
- if a string contains max 5 words (Here a word is an alphabetic or alphanumeric string) and this string can't be blank (one space)
I try with this : ( just to match 5 words)
@Pattern(message="max 5 words please" , regexp="^[a-zA-Z+#\-.0-9]{1,5}(\s[a-zA-Z+#\-.0-9]{1,5}){0,4}$") String keywords;
but my Eclipse IDE says : Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
原文:https://stackoverflow.com/questions/8403201
最满意答案
我已将测试脚本从Coffee Script移植到JavaScript并在NodeUnit中运行,见下文。
虽然我改变了两件事。 首先,而不是:
@db.connection.on 'open', () ->
我这样做了(在Coffee Script中):
mongoose.connection.on 'open', () ->
其次,我已经颠倒了顺序或者注册了回调并建立了连接。
生成的JavaScript:
var mongoose = require('mongoose'); var models = require('./models'); var Task = models.Task; var db; module.exports = { setUp: function(callback) { try { //db.connection.on('open', function() { mongoose.connection.on('open', function() { console.log('Opened connection'); callback(); }); db = mongoose.connect('mongodb://localhost/test_1'); console.log('Started connection, waiting for it to open'); } catch (err) { console.log('Setting up failed:', err.message); } }, tearDown: function(callback) { console.log('In tearDown'); try { console.log('Closing connection'); db.disconnect(); callback(); } catch (err) { console.log('Tearing down failed:', err.message); } }, getTasks: function(test) { console.log('running first test'); Task.find({}, function (err, result) { if (!err) { console.log('results' + result); test.ok(result); } else { console.log('error' + err); } test.ifError(err); test.done(); }); } };
Models.js
var mongoose = require('mongoose'); var TaskSchema = new mongoose.Schema({ field1: String, field2: Number }); module.exports.Task = mongoose.model('Task', TaskSchema);
结果输出:
$ ~/node_modules/nodeunit/bin/nodeunit test.js test.js Started connection, waiting for it to open Opened connection running first test results In tearDown Closing connection ✔ getTasks OK: 2 assertions (198ms)
我必须注意,当MongoDB没有运行/不可连接时,测试失败就像你说的那样。 所以你可能也想检查你的连接字符串。
I've ported the test script from Coffee Script to JavaScript and ran it in NodeUnit, see below.
There were two things I have changed though. First, instead of:
@db.connection.on 'open', () ->
I did this (in Coffee Script):
mongoose.connection.on 'open', () ->
Second, I've reversed the order or registering the callback and making the connection.
The resulting JavaScript:
var mongoose = require('mongoose'); var models = require('./models'); var Task = models.Task; var db; module.exports = { setUp: function(callback) { try { //db.connection.on('open', function() { mongoose.connection.on('open', function() { console.log('Opened connection'); callback(); }); db = mongoose.connect('mongodb://localhost/test_1'); console.log('Started connection, waiting for it to open'); } catch (err) { console.log('Setting up failed:', err.message); } }, tearDown: function(callback) { console.log('In tearDown'); try { console.log('Closing connection'); db.disconnect(); callback(); } catch (err) { console.log('Tearing down failed:', err.message); } }, getTasks: function(test) { console.log('running first test'); Task.find({}, function (err, result) { if (!err) { console.log('results' + result); test.ok(result); } else { console.log('error' + err); } test.ifError(err); test.done(); }); } };
Models.js
var mongoose = require('mongoose'); var TaskSchema = new mongoose.Schema({ field1: String, field2: Number }); module.exports.Task = mongoose.model('Task', TaskSchema);
And the resulting output:
$ ~/node_modules/nodeunit/bin/nodeunit test.js test.js Started connection, waiting for it to open Opened connection running first test results In tearDown Closing connection ✔ getTasks OK: 2 assertions (198ms)
I do have to note that when MongoDB was not running/not connectable, the tests were failing like you stated. So you might want to check your connection string as well.
相关问答
更多-
数据库连接仍处于打开状态并正在侦听事件。 要使脚本结束,您需要关闭它: location.save(function(err){ if (err) { throw new Error(err); } console.log(location); mongoose.connection.close(); }); The database connection is still open and listening for events. For the s ...
-
使用.exec。 它配置填充。 Site.find({}).populate('userid').exec(function (err, postIn) { if (err) { throw err } else { res.send(postIn); } }); use .exec. It configures the populate. Site.find({}).populate('userid' ...
-
如何通过节点单元和mongoose返回异步结果?(How do I get an asynchronous result back with node unit and mongoose?)[2023-10-03]
我已将测试脚本从Coffee Script移植到JavaScript并在NodeUnit中运行,见下文。 虽然我改变了两件事。 首先,而不是: @db.connection.on 'open', () -> 我这样做了(在Coffee Script中): mongoose.connection.on 'open', () -> 其次,我已经颠倒了顺序或者注册了回调并建立了连接。 生成的JavaScript: var mongoose = require('mongoose'); var models = ... -
异步猫鼬调用(Asynchronous Mongoose Calls)[2019-12-26]
(更新:此解决方案有一个小错误。由于某种原因,当一个字段配对时,它应该停止,但它会保持配对和配对..) 从Molda的建议我设法得到一个工作的异步解决方案: match : function(){ Bet.find({"paired" : false}, {_id:1, bet:1, market:1, odds:1, student:1, to_match:1, stake:1}) .sort({createdAt : 1}).exec(function(err, results){ ... -
如果没有错误,则应该在前一个方法的回调之后调用每个函数,而不是使用createData()方法。 例如 : function createGame(){ new Game({ name: 'Legend of Zelda: Ocarina of Time' , developer: 'Nintendo' , released: new Date('November 21, 1998') }).save(function(err) { if(err) { ...
-
如果你展开内部调用的json,它可能会有所帮助 [ [ { "symbol": "A", "_id": "552faf5c0aac9578428320da" }, { "symbol": "B", "_id": "552faf5c0aac9578428320db" }, { "symbol": "C", "_id": "552faf5c0aac9578428320dc" } ], ...
-
你混淆了两种思维方式: 承诺(与你的情况异步/等待) 回电话 只使用一个 try { const user = await mydata.save(); res.location(`/mydata/id/${user._id}`); // Other stuff ... } catch(err) { // Handle the errors } 在这里你可以得到一篇关于承诺进入猫鼬的文章。 You are mixing up two way of thinking : Prom ...
-
在mongoose / mongodb / node中循环使用异步回调(Loop with asynchronous callbacks in mongoose/mongodb/node)[2023-04-12]
我想你想用async之类的东西来协调这些请求; map()似乎是个不错的选择: Author.find({}, function (err, authors) { async.map(authors, function(author, done) { Book.count({author: author._id}, function(err, count) { if (err) done(err); else { done(nu ... -
注意:这是一个编辑,我的原始答案是相当不同的 所以这有点令人困惑,但Mongoose返回MongooseDocument对象而不是普通的JSON对象 。 因此,在obj上使用.lean()方法将其转换为JSON,然后从那里开始根据需要更改它。 感谢Ze Jibe。 Note: This is an edit, my original answer was rather different So this is a little confusing but Mongoose returns MongooseD ...
-
请改用async库中的filter功能。 UPDATE 你的尝试非常接近,你只需要将结果提供给回调而不是返回它: async.filter(myArray, function(elem, callback){ MyCollection.findOne({_id : elem}, function(err, doc) { callback(err == null && doc != null); }); }, function(results){ // results is myArra ...