2014-04-03 98 views
0

好的,所以我试图在服务器端进行验证。我正在为我的Android应用程序使用Windows Azure移动服务。验证在Javascript/Node.js中完成。Azure - 服务器验证

我一直在尽我最大的努力找到解决我的问题,并偶然发现[此链接](http://blogs.msdn.com/b/carlosfigueira/archive/2012/09/21/playing-with-the-query-object-in-read-operations-on-azure-mobile-services.aspx)!

我打算使用regexp验证对象,然后再将它保存到数据库。

我会理解如何做到这一点'预查询',但由于我需要访问使用正则表达式,我必须执行'后查询'过滤。

下面是我有(到目前为止)的代码,但我想知道如何验证许多字段并为每个无效字段传递适当的错误消息。如果全部都是有效的,那么坚持数据库。

在此先感谢!

function insert(item, user, request) { 

    var userTable = tables.getTable('User'); 
    userTable.where({email: item.email}).read({ 
        success: emailExists 
        }); 

    function emailExists(existingItems) 
    { 
     if (existingItems.length > 0) 
     { 
        request.respond(statusCodes.CONFLICT, 
         "An account is already registered with this email!."); 
       } 
       else 
       { 
        // Insert the item as normal. 
        request.execute({ 
         success: function (results) 
         { 
          var regexEmail = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
          var filtered = results.filter(function(item) 
          { 
          return regexEmail.test(item.email); 
          }); 

          request.respond(statusCodes.OK, filtered); 
         } 
       }); 
      } 
    } 
} 

回答

1

如果我理解你想要正确地做什么,你首先需要验证输入的电子邮件对数据库中的项目(以保持唯一性),然后在插入之前验证输入等领域。如果是这种情况,那么在查询验证(以防止重复的电子邮件)之后,您可以单独验证项目字段,如this document中所示。下面的代码显示了这种验证的一个例子。

function insert(item, user, request) { 

    var userTable = tables.getTable('User'); 
    userTable.where({email: item.email}).read({ 
         success: emailExists 
        }); 

    function emailExists(existingItems) 
    { 
     if (existingItems.length > 0) 
     { 
      request.respond(statusCodes.CONFLICT, 
       "An account is already registered with this email!."); 
     } 
     else 
     { 
      // Validate fields *before* inserting 
      var regexEmail = /^(([^<>()[\]\\.,;:\[email protected]\"]+(\.[^<>()[\]\\.,;:\[email protected]\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
      if (!regexEmail.test(item.email)) { 
       request.respond(statusCodes.BAD_REQUEST, { error: 'E-mail is invalid' }); 
       return; 
      } 

      if (!item.name || item.name.length < 10) { 
       request.respond(statusCodes.BAD_REQUEST, { error: 'Item must have a name of at least 10 characters' }); 
       return; 
      } 

      // If all validation succeeded, then insert the item 
      request.execute(); 
     } 
    } 
} 
+0

正是我在找什么,对不起,如果我让它听起来令人困惑!谢谢 ! – GermaineJason