Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add documentation for sometimes rule, and fix nested sometimes bug #437

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,18 @@ The field under validation must be present and not empty only when any of the ot

The field under validation must be present and not empty only when all of the other specified fields are not present.

#### sometimes

In some situations, you may wish to run validation checks against a field only if that field is present in the data being validated. To quickly accomplish this, add the sometimes rule to your rule list:

```js
let rules = {
email: 'sometimes|required|email'
}
```

In the example above, the email field will only be validated if it is present in the input.

#### same:attribute

The given field must match the field under validation.
Expand Down
37 changes: 29 additions & 8 deletions dist/validator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/*! validatorjs - 2020-12-03 */
/*! validatorjs - 2021-09-08 */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Validator = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
function AsyncResolvers(onFailedOne, onResolvedAll) {
this.onResolvedAll = onResolvedAll;
Expand Down Expand Up @@ -1574,7 +1574,7 @@ Validator.prototype = {
var attributeRules = this.rules[attribute];
var inputValue = this._objectPath(this.input, attribute);

if (this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute)) {
if (this._passesOptionalCheck(attribute)) {
continue;
}

Expand Down Expand Up @@ -1639,7 +1639,7 @@ Validator.prototype = {
var attributeRules = this.rules[attribute];
var inputValue = this._objectPath(this.input, attribute);

if (this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute)) {
if (this._passesOptionalCheck(attribute)) {
continue;
}

Expand Down Expand Up @@ -1740,7 +1740,6 @@ Validator.prototype = {
* @return {object}
*/
_parseRules: function (rules) {

var parsedRules = {};
rules = this._flattenObject(rules);

Expand All @@ -1751,8 +1750,6 @@ Validator.prototype = {
this._parseRulesCheck(attribute, rulesArray, parsedRules);
}
return parsedRules;


},

_parseRulesCheck: function (attribute, rulesArray, parsedRules, wildCardValues) {
Expand Down Expand Up @@ -1804,7 +1801,6 @@ Validator.prototype = {
},

_replaceWildCards: function (path, nums) {

if (!nums) {
return path;
}
Expand Down Expand Up @@ -1839,6 +1835,7 @@ Validator.prototype = {

this.messages._setCustom(customMessages);
},

/**
* Prepare rules if it comes in Array. Check for objects. Need for type validation.
*
Expand All @@ -1864,14 +1861,38 @@ Validator.prototype = {
return rules;
},

/**
* Determine if the attribute passes any optional check.
*
* @param {string} attribute
* @return {boolean}
*/
_passesOptionalCheck: function (attribute) {
return this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute);
},

/**
* Determines if the attribute is supplied with the original data object.
*
* @param {array} attribute
* @return {boolean}
*/
_suppliedWithData: function (attribute) {
return this.input.hasOwnProperty(attribute);
function hasNested(obj, key, ...rest) {
if (obj === undefined) {
return false;
}

if (rest.length == 0 && obj.hasOwnProperty(key)) {
return true;
}

return hasNested(obj[key], ...rest);
}

var keys = attribute.split('.');

return hasNested(this.input, ...keys);
},

/**
Expand Down
16 changes: 16 additions & 0 deletions spec/sometimes-rule.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,20 @@ describe("sometimes validation pass rules", function() {
const validator = new Validator({ username: "test" }, { username: "username", email: "email|sometimes" });
validator.passes(done);
});

it("should pass when the nested property is passed with data", function() {
const validator = new Validator(
{ user: { firstname: "Johnny", lastname: "Appleseed" } },
{ "user.firstname": "required", "user.lastname": "sometimes|required|string" }
);
expect(validator.passes()).to.be.true;
});

it("should fail validation when the nested property is passed with invalid data", function() {
const validator = new Validator(
{ user: { firstname: "Johnny", lastname: '' } },
{ "user.firstname": "required", 'user.lastname': "sometimes|required|string" }
);
expect(validator.passes()).to.be.false;
});
});
37 changes: 29 additions & 8 deletions src/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ Validator.prototype = {
var attributeRules = this.rules[attribute];
var inputValue = this._objectPath(this.input, attribute);

if (this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute)) {
if (this._passesOptionalCheck(attribute)) {
continue;
}

Expand Down Expand Up @@ -121,7 +121,7 @@ Validator.prototype = {
var attributeRules = this.rules[attribute];
var inputValue = this._objectPath(this.input, attribute);

if (this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute)) {
if (this._passesOptionalCheck(attribute)) {
continue;
}

Expand Down Expand Up @@ -222,7 +222,6 @@ Validator.prototype = {
* @return {object}
*/
_parseRules: function (rules) {

var parsedRules = {};
rules = this._flattenObject(rules);

Expand All @@ -233,8 +232,6 @@ Validator.prototype = {
this._parseRulesCheck(attribute, rulesArray, parsedRules);
}
return parsedRules;


},

_parseRulesCheck: function (attribute, rulesArray, parsedRules, wildCardValues) {
Expand Down Expand Up @@ -286,7 +283,6 @@ Validator.prototype = {
},

_replaceWildCards: function (path, nums) {

if (!nums) {
return path;
}
Expand Down Expand Up @@ -321,6 +317,7 @@ Validator.prototype = {

this.messages._setCustom(customMessages);
},

/**
* Prepare rules if it comes in Array. Check for objects. Need for type validation.
*
Expand All @@ -346,14 +343,38 @@ Validator.prototype = {
return rules;
},

/**
* Determine if the attribute passes any optional check.
*
* @param {string} attribute
* @return {boolean}
*/
_passesOptionalCheck: function (attribute) {
return this._hasRule(attribute, ['sometimes']) && !this._suppliedWithData(attribute);
},

/**
* Determines if the attribute is supplied with the original data object.
*
* @param {array} attribute
* @param {string} attribute
* @return {boolean}
*/
_suppliedWithData: function (attribute) {
return this.input.hasOwnProperty(attribute);
function hasNested(obj, key, ...rest) {
if (obj === undefined) {
return false;
}

if (rest.length == 0 && obj.hasOwnProperty(key)) {
return true;
}

return hasNested(obj[key], ...rest);
}

var keys = attribute.split('.');

return hasNested(this.input, ...keys);
},

/**
Expand Down