gpt4 book ai didi

javascript - 如何在 Sails.js 中将 Json 验证消息转换为字符串消息?

转载 作者:行者123 更新时间:2023-11-28 07:01:15 26 4
gpt4 key购买 nike

我正在尝试在 sails.js 中实现自定义验证。我设法获取错误消息,但它是 Json 格式。我想将其转换为

我的模型

    module.exports = {
attributes: {
username: {
type: 'string',
required: true
},
email: {
type: 'string',
required: true,
unique: true
}
},

//model validation messages definitions
validation_messages: { //hand for i18n & l10n

email: {
required: 'Email is required',

unique: 'Email address is already taken'
},
username: {
required: 'Username is required'
}
}
};

我的 Controller :

        create:function(req,res){
console.log('create');
console.log(req.param('username'));
console.log(req.param('email'));

var Username=req.param('username');
var Email=req.param('email');

//console.log(Username);
//console.log(Username);
var params=req.params.all();
console.log(params);
Employee.create(params).exec(function(err,model){
if(err){
if (err.ValidationError) {
errors = HandleValidation.transformValidation(Employee, err.ValidationError);
console.log(errors);
res.json({
success:false,
errors: errors
})
};
}

if(model)
{
res.json(model);
}

});

}

Js:

   $("form").submit(function(){
var username=$('#username').val();
var email=$('#email').val();
var id=$(this).attr('rel');

$.post('/create', {
username:username,
email:email
}).success(function (data) {


//var jsonObj = JSON.parse(data);

alert(JSON.stringify(data));

}).fail(function (data) {

alert((JSON.stringify(data)));
});


});

如果我提交空表单,错误消息将显示如下:

            { username: '', email: '' }
{ email: [ { required: 'Email is required' } ],
username: [ { required: 'Username is required' } ] }

我想要这样的输出:

                 Email is required
Username is required

请帮忙。任何帮助将不胜感激

最佳答案

data 是一个对象。迭代它以获得你想要的。

基于字符串化 JSON 对象的外观:

var errors = data.errors
var errorsString = ""
for(var field in errors) {
if(errors.hasOwnProperty(field)) {
for (var i = 0; i < errors[field].length; i++) {
error = errors[field][i]
for (var errorType in error) {
errorsString += error[errorType] + "\n"
}
}
}
}
alert(errorsString)

关于javascript - 如何在 Sails.js 中将 Json 验证消息转换为字符串消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32118275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com