【问题标题】:Form validation using Meteor/React/SimpleSchema使用 Meteor/React/SimpleSchema 进行表单验证
【发布时间】:2017-02-11 13:28:12
【问题描述】:

我对 Meteor 还很陌生。我一直在尝试找到一种方法来向我的 React 组件显示验证错误消息,但没有成功。

这是位于我的导入目录中的 employees.js 文件

import {Mongo} from 'meteor/mongo';
import {Meteor} from 'meteor/meteor';
import {check, Match} from 'meteor/check'
import SimpleSchema from 'simpl-schema';

export const Employees = new Mongo.Collection('employees');

const Schemas = {};

Schemas.Employee = new SimpleSchema({
  name: {
    type: String,
    min: 2,
  },
  email: {
    type: String,
    min: 2
  },
  phone: {
    type: String
  }
});

Meteor.methods({
  'employees.insert': function (employee) {
    check(employee, Schemas.Employee)
  }
});

这里是我处理提交的代码片段。流星方法调用很好,只是我无法取回errors对象来显示错误。

import React, {Component} from 'react';
import {TextField, RaisedButton} from 'material-ui';
import {Flex, Box} from 'reflexbox';
import injectTapEventPlugin from 'react-tap-event-plugin';

injectTapEventPlugin();

class EmployeeForm extends Component {

  ... 

  handleSubmit(event) {
    event.preventDefault();
    this.handleClear(() => {
      Meteor.call('employees.insert', this.state, (error, response) => {
        console.log('error', error);
      })
    })
  }

  ...
}

export default EmployeeForm;

任何帮助我都会非常感激。关于如何做到这一点的文档很少 - 嗯,它是在我搜索互联网时。

谢谢

【问题讨论】:

    标签: reactjs meteor simple-schema


    【解决方案1】:

    我认为您不能将simple schemacheck 一起使用。通常对于普通的 Meteor 方法,我使用这段代码来验证数据:

    Meteor.methods({
      'employees.insert': function (employee) {
    
        try {
          Schemas.Employee.validate(employee);
        } catch (e) {
          throw new Meteor.Error('error', e.message);
        }
    
        // ...
      }
    });
    

    这样您将在客户端收到错误消息。我也鼓励你看看validated-method,这是定义 Meteor 方法的另一种方式,它有许多有用的 mixin,包括使用简单的 schema mixin 进行验证。

    【讨论】:

      【解决方案2】:

      我的解决方案非常基于 Khang 的回答。

      Employees.attachSchema(Schemas.Employee);
      
      Meteor.methods({
        'employees.insert': function (employee) {
            Employees.insert(employee, { removeEmptyStrings: false }, (error, response) => {
              if (error) {
                throw new Meteor.Error('error', error.invalidKeys);
              }
            });
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2016-04-30
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 2016-01-08
        • 1970-01-01
        • 2017-02-28
        • 2016-08-23
        • 2021-08-17
        相关资源
        最近更新 更多