Make SimpleSchema custom() function reactive
See original GitHub issueHi aldeed.
I am currently using the custom()
function of SimpleSchema
to add a custom validation for many fields of my forms.
Basically, i want to add a custom verification to check if a username is available :
username: {
type: String,
regEx: /^[a-z0-9A-Z_]{3,15}$/,
label: "Username",
// custom validation for username availability
custom: function () {
Meteor.call('accountsIsUsernameAvailable', this.value, function (error, result) {
if (!result)
Session.set("usernameAvailability", "usernameNotAvailable");
else
Session.remove("usernameAvailability");
});
return (Session.get("usernameAvailability"));
}
}
I am using a method of course because i obviously dont want to publish all the usernames of my database to the client. Because i want a result from these method, i set a callback and the method run asynchronously, and this is where is my issue.
To be sure that i will actually return a result from custom()
, u can see in the code example above that i use Session
as a reactive data source to make sure the custom function will return the result a soon as it arrive. In fact, there is two return for each excecution of custom()
, but i don’t really care.
What i would like to propose, is a way to avoid the use of Session
. I prefer in every case to limit the use of Session
to do not polluate the namespace.
I just wrote my code with Session
to test the method inside custom()
, but now i am gonna to write my own reactive data source for this purpose, according this tutorial : https://www.eventedmind.com/feed/meteor-build-a-reactive-data-source.
I am wondering if it would be possible to implement such a thing in SimpleSchema
custom()
function ? I don’t know how it work internally in SimpleSchema
, but i guess you are invalidating a field based on the return of custom()
. Would it be possible to offer a property this.result
inside custom()
, let the user fill it with the same way (non-string for success – string for error) and track this with a Deps.Dependency
. Then on the change of this property, do the invalidation methodology inside SimpleSchema
.
I am maybe wrong about this, if so, forgive me, i’m just sharing my thought because i was thinking of that when i was writting my code.
Regards,
William
<bold>EDIT:</bold> I don’t think that the context of custom()
would be available in the Meteor.Method
that have to set the this.result
property, but maybe using _.bind
would be helpfull in this case, and solve the problem of accessibility.
Issue Analytics
- State:
- Created 9 years ago
- Comments:8
Top GitHub Comments
In that case, just put my approach into your custom function:
The
custom
function doesn’t have to return anything, and when you do return a string, it is essentially identical to callingaddInvalidKeys
, so this approach is equivalent to returning a custom error string after a short delay.I have problem with
onSuccess Hook
, it run beforecustom validate