Mahendra Garg
Mahendra Garg

Reputation: 536

Unique Field in Meteor AutoForm

I have a Meteor AutoForm collection schema with the following field and I am trying to make it unique. It doesn't allow the same value in the same case but when I change the case of the value, value get inserted, so how can I prevent to insert duplicate value with different case?

Like Test, TEST, TesT all having the same spell so it should not get inserted.

I tried this:

Schemas.Organisation = new SimpleSchema({
    company: {
        type: String,
        max: 200,
        unique: true,
        autoValue: function () {
            if (this.isSet && typeof this.value === "string") {
                return this.value.toLowerCase();
            }
        },
        autoform:{
            label: false,
            afFieldInput: {
                placeholder: "Enter Company Name",
            }
        }
    }
  })

But it is not let me inserted the duplicate value but it converting to all lower case while saving in the db. So how can I save the value as user entered, but value should not have same spell?

Upvotes: 3

Views: 599

Answers (1)

Matthias A. Eckhart
Matthias A. Eckhart

Reputation: 5156

This can be achieved by using a custom client-side validation. If you don't want to publish all documents of your Organisation collection to every client, you could use an asynchronous validation approach, for example:

Organisations = new Mongo.Collection("organisations");

Organisations.attachSchema(new SimpleSchema({
    company: {
        type: String,
        max: 200,
        unique: true,
        custom: function() {
            if (Meteor.isClient && this.isSet) {
                Meteor.call("isCompanyUnique", this.value, function(error, result) {
                    if (!result) {
                        Organisations.simpleSchema().namedContext("insertCompanyForm").addInvalidKeys([{
                            name: "company",
                            type: "notUnique"
                        }]);
                    }
                });
            }
        },
        autoValue: function() {
            if (this.isSet && typeof this.value === "string") {
                return this.value.toLowerCase();
            }
        },
        autoform: {
            label: false,
            afFieldInput: {
                placeholder: "Enter Company Name",
            }
        }
    }
}));

if (Meteor.isServer) {
  Meteor.methods({
    isCompanyUnique: function(companyName) {
      return Organisations.find({
        company: companyName.toUpperCase()
      }).count() === 0;
    }
  });
}

<body>
  {{> quickForm collection="Organisations" id="insertCompanyForm" type="insert"}}
</body>

Here's a MeteorPad.

Upvotes: 1

Related Questions