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

时间:2015-08-20 12:27:30

标签: javascript sails.js

我正在尝试在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'
        }
    }
};

我的控制器:

        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

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

1 个答案:

答案 0 :(得分:0)

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)