0

I'm learning how to use Meteor and am currently looking at using the check package to validate user input, using the tutorial at: http://meteortips.com/first-meteor-tutorial/methods/.

I'm trying to use the Match.Integer pattern inside a method (addPlayer, say) to ensure data entered into a particular field (passed to the addPlayer method via the initialScore parameter) is a valid integer, which works fine when calling addPlayer through the console. However, when entering data via the form (which calls addPlayer when submitted) this doesn't work properly since the entered data is of the String type.

I was considering applying the Number function to the entered data before using Match.Integer but am thinking this is a bad idea since some non-numerical values would be accepted.

Would it be a good idea to have my own isInteger function, such as:

function isInteger(n) {
  return n == +n && n == (n|0);
}

(from https://stackoverflow.com/a/3885844/3806231, but with === replaced with == to allow form data, of String type, to be checked)

and call this before applying the Number function as described above? For example:

Meteor.methods({

  'addPlayer': function(initialScore) {
    if (isInteger(initialScore)) {
      check(Number(initialScore), Match.Integer);
    }
  }

});

Something like this seems quite long-winded and expensive just to validate an integer. Before using Meteor, I would just call something like the isInteger method, but now I'm using Meteor I want to make use of the available packages to save writing some of this standard validation code myself.

Is there a better way of doing this?

Community
  • 1
  • 1
Ruben9922
  • 766
  • 1
  • 11
  • 16
  • 1
    If it's a number field, don't even allow the user to enter non-numbers to begin with! Make an onChange event and check the regex against `/[0-9]/ ` (or `/[\-0-9]/ ` if negative integers are allowed). – Michel Floyd Jul 01 '16 at 04:07
  • 1
    @MichelFloyd Oh yeah, thanks. Thinking I could do that inside a jQuery `.on('input')` event so it fires at every change of the text rather than only when losing focus, or possibly put it into a `Match.Where` inside a `check`. – Ruben9922 Jul 01 '16 at 17:28
  • @MichelFloyd Also, should the `onChange` event handler code be sent to just the client? – Ruben9922 Jul 01 '16 at 17:32
  • Yes, just do initial validation on the client in the UI before you send it to the server and then check it again on the server using `check()`. Give the user feedback asap which means avoid the server roundtrip for typos/fat fingers. – Michel Floyd Jul 01 '16 at 17:40
  • You don't need a jQuery event handler, you can just have a Template event. – Michel Floyd Jul 01 '16 at 17:58
  • @MichelFloyd Oh yeah, forgot about that. Also that'll allow me to use the Bootstrap success/error validation states for the form inputs. And oh yeah, forgot about the `Template` events as well :P – Ruben9922 Jul 02 '16 at 17:07

0 Answers0