javascript - 在 Javascript 中验证对象形状的简单方法

标签 javascript validation shapes

我想知道是否有一种简单的方法可以在 Javascript 中验证对象的形状。

现在,我有一个函数可以像这样验证端点对象的形状:

function validateEndpointShape(endpoint: any, hasId: boolean): boolean 
{
return endpoint
&& (hasId ? typeof endpoint.id === 'string' : true)
&& typeof endpoint.name === 'string'
&& typeof endpoint.description === 'string'
&& typeof endpoint.url === 'string'
&& GenericApiEndpointMethods[endpoint.method] !== undefined
&& ApiEndpointTypes[endpoint.apiEndpointType] !== undefined
&& endpoint.group
&& typeof endpoint.group.groupPublicKey === 'string'
&& typeof endpoint.group.groupName === 'string'
&& typeof endpoint.reason === 'string'
&& typeof endpoint.isPublic === 'boolean'
&& typeof endpoint.isActive === 'boolean'
&& authTypes[endpoint.authType] !== undefined
&& Array.isArray(endpoint.parameters)
&& Array.isArray(endpoint.headers);
}

这可能会变得麻烦和笨拙。而且我不想为我创建的每个对象都执行此操作。

当端点进入我们的云 firebase 函数时,我们必须对其进行一系列验证,以便我们知道何时拒绝不良数据。端点的形状是这些验证之一。

我试过这样做:

Delete req.body.reason;
req.body[‘extraField’] = ‘xxx’;
Const endpoint: GenericApiEndpoint = req.body;
console.log(‘endpoint =‘, endpoint);

但是 Javascript 不关心。它将无缘无故地接受端点(必填字段)和带有 extraField(模型中不存在的字段)并将其分配给类型为 GenericApiEndpoint 的对象。 Endpoint 无缘无故地打印出来,带有 extraField。

我也试过:

Const endpoint = <GenericApiEndpoint>req.body;

...但是 Javascript 也不关心这些。

有人知道在 Javascript 中验证对象形状的简单方法吗?

最佳答案

验证数据的方法有很多种,我想说的是,在任何您希望数据持久存在并匹配特定模型的系统中,您都需要某种字段验证。 ORM 通常会这样做,但您也可以使用以下库:

基本上底线是,如果您想要验证对象以确保它们符合特定形状(模型/架构),您必须事先定义该形状。

关于javascript - 在 Javascript 中验证对象形状的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398570/

相关文章:

javascript - 如何在 Vue 中将数据从组件传递到实例

javascript - 执行在await Promise.all后停止

xml - 如何使用 Saxon Home Edition (HE) 9.4 根据 XSD 验证 XML

css - 有没有更简单的方法来使用 css 创建这个形状? (包括 jsfiddle)

c# - 如果形状的高度大于表单的高度,则显示滚动条

JavaFX:绘制无限符号并向前移动

javascript - 如何在ReactJS中的三元运算符中使用OR条件

javascript - Mongoose 使用方法将模式添加到模式中

ruby-on-rails - 为新的 ActiveRecord 验证指定错误消息(存在)

php - 如何检查 $_GET 数组中的变量是否为整数?