Andrew Zielinski
Andrew Zielinski

Reputation: 23

Form validation using Meteor/React/SimpleSchema

I'm fairly new to Meteor. I've been trying to find a way to display validation error messages to my React component but I've had no success.

This is employees.js file which resides in my imports directory

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)
  }
});

And here is a snipped of my code which handles the submit. The meteor method is called fine, it's just that I can't get the errors object back to display the 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;

Any help would me much appreciated. Documentation on how to do this is slim - well it was on my search of the interwebs.

Thanks

Upvotes: 2

Views: 577

Answers (2)

Andrew Zielinski
Andrew Zielinski

Reputation: 23

My solution based very much on Khang's answer.

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);
        }
      });
  }
});

Upvotes: 0

kkkkkkk
kkkkkkk

Reputation: 7738

I do not think you could use simple schema with check. Usually for normal Meteor methods, I use this code to validate data:

Meteor.methods({
  'employees.insert': function (employee) {

    try {
      Schemas.Employee.validate(employee);
    } catch (e) {
      throw new Meteor.Error('error', e.message);
    }

    // ...
  }
});

This way you will receive the error message in client. I also encourage you to have a look at validated-method, this is another way to define Meteor methods and it has many useful mixins including validation with simple schema mixin.

Upvotes: 1

Related Questions