首页 \ 问答 \ @Pattern,JSR303 bean验证:正则表达式检查最多5个单词,而不是空白(@Pattern , JSR303 bean validation : regex check max 5 words and not blank)

@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
更新时间:2022-01-18 18:01

最满意答案

我已将测试脚本从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' ...
  • 我已将测试脚本从Coffee Script移植到JavaScript并在NodeUnit中运行,见下文。 虽然我改变了两件事。 首先,而不是: @db.connection.on 'open', () -> 我这样做了(在Coffee Script中): mongoose.connection.on 'open', () -> 其次,我已经颠倒了顺序或者注册了回调并建立了连接。 生成的JavaScript: var mongoose = require('mongoose'); var models = ...
  • (更新:此解决方案有一个小错误。由于某种原因,当一个字段配对时,它应该停止,但它会保持配对和配对..) 从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 ...
  • 我想你想用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 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)