2

I am trying to validate single values by using validate.js library but I am getting udefined result from validate.single() function.

var test1 = "test12345";
var test2 = "1234";
var test3 = "";

var constraints1 = {
  length: {
    is: 4
  }
}

var constraints2 = {
  length: {
    minimum: 4
  }
}

var constraints3 = {
  length: {
    maximum: 4
  }
}

console.log('Testing for exact length');
console.log(validate.single(test1, constraints1));
console.log(validate.single(test2, constraints1));
console.log(validate.single(test3, constraints1));

console.log('Testing for min length');
console.log(validate.single(test1, constraints2));
console.log(validate.single(test2, constraints2));
console.log(validate.single(test3, constraints2));

console.log('Testing for max length');
console.log(validate.single(test1, constraints3));
console.log(validate.single(test2, constraints3));
console.log(validate.single(test3, constraints3));

Result from above example:

[Log] Testing for exact length
[Log] ["is the wrong length (should be 4 characters)"]
[Log] undefined
[Log] undefined
[Log] Testing for min length
[Log] undefined
[Log] undefined
[Log] undefined
[Log] Testing for max length
[Log] ["is too long (maximum is 4 characters)"]
[Log] undefined
[Log] undefined

Why undefined?

JSFiddle: https://jsfiddle.net/3s8ckdkc/13/

Primoz Rome
  • 10,379
  • 17
  • 76
  • 108

1 Answers1

1

Please have a look at the home page of the library you're using.

In the examples there is the pass case that is indicating returning undefined.

In short, the library returns a value just if there is a contraint broken.

Otherwise undefined is returned.

The library consider the empty, null or undefined as valid values.

From the page:

Important! One thing that is a bit unorthodox is that most validators will consider empty values (null, undefined, whitespace only strings etc) valid values. So for example adding a constraint of at least 6 characters will be like saying If the attribute is given it must be at least 6 characters. This differs from example Ruby on Rails where validators instead have the allow_nil option. I find it quite common that you want to have constraints on an optional attribute.

That means the test3 where you put an empty string is always valid as it is an empty string, doesn't matter the constraint you have.

Mario Santini
  • 2,905
  • 2
  • 20
  • 27
  • Ok I see that but I am getting undefined also where constraint is broken...? For example `test3 = ""` should be broken with all three constraints in my example but also getting beck `Undefined` – Primoz Rome Aug 27 '16 at 08:23
  • Thanks, strange logic if u ask me – Primoz Rome Aug 27 '16 at 12:18
  • There is this mark in the docs which `Important! Most validators consider empty values (null, undefined, whitespace only strings etc) valid values so make sure you use the presence validator on attributes that are required.` – Primoz Rome Aug 28 '16 at 08:36