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

React / Yup / Formik / GraphQL compatible #795

Closed
wants to merge 1 commit into from
Closed
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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@
"homepage": "https://github.com/DavyJonesLocker/client_side_validations",
"scripts": {
"build": "standard --verbose && rollup -c",
"test": "test/javascript/run-qunit.js"
"test": "test/javascript/run-qunit.js",
"jest": "jest yup/*.test.js"
},
"devDependencies": {
"@babel/core": "^7.9.6",
"@babel/preset-env": "^7.9.6",
"@rollup/plugin-babel": "^5.0.2",
"@rollup/plugin-node-resolve": "^8.0.0",
"chrome-launcher": "^0.13.2",
"jest": "^25.5.4",
"puppeteer-core": "^3.1.0",
"rollup": "^2.10.9",
"rollup-plugin-copy": "^3.3.0",
Expand Down
257 changes: 257 additions & 0 deletions yup/ClientSideValidations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
const NUMBER_FORMAT = { separator: ".", delimiter: "," };
const NUMERICALITY_DEFAULT = new RegExp(
"^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$"
);
const NUMERICALITY_ONLY_INTEGER = new RegExp("^[+-]?\\d+$");

class ClientSideValidations {
absence(value = "", options = {}) {
if (!/^\s*$/.test(value)) {
return options.message;
}
return null;
}

presence(value = "", options = {}) {
if (/^\s*$/.test(value)) {
return options.message;
}
return null;
}

acceptance(value = true, options = {}) {
if (typeof value === "boolean") {
if (value !== true) {
return options.message;
}
}

let ref;

if (typeof value === "string") {
if (
value !==
(((ref = options.accept) != null ? ref.toString() : void 0) || "1")
) {
return options.message;
}
}

return null;
}

format(value = "", options = {}) {
const message = this.presence(value, options);
if (message) {
if (options.allow_blank === true) {
return null;
}
return message;
}

if (
options.with &&
!new RegExp(options.with.source, options.with.options).test(value)
) {
return options.message;
}

if (
options.without &&
new RegExp(options.without.source, options.without.options).test(value)
) {
return options.message;
}

return null;
}

numericality(value = "", options = {}) {
if (
options.allow_blank === true &&
this.presence(value, { message: options.messages.numericality })
) {
return null;
}

value = value
.trim()
.replace(new RegExp("\\" + NUMBER_FORMAT.separator, "g"), ".");

if (options.only_integer && !NUMERICALITY_ONLY_INTEGER.test(value)) {
return options.messages.only_integer;
}

if (!NUMERICALITY_DEFAULT.test(value)) {
return options.messages.numericality;
}

const NUMERICALITY_CHECKS = {
greater_than(a, b) {
return a > b;
},
greater_than_or_equal_to(a, b) {
return a >= b;
},
equal_to(a, b) {
return a === b;
},
less_than(a, b) {
return a < b;
},
less_than_or_equal_to(a, b) {
return a <= b;
},
};

for (var check in NUMERICALITY_CHECKS) {
const check_function = NUMERICALITY_CHECKS[check];
if (options[check] != null) {
const checkValue = (() => {
if (!isNaN(parseFloat(options[check])) && isFinite(options[check])) {
return options[check];
}
})();

if (checkValue == null || checkValue === "") {
return null;
}

if (!check_function(parseFloat(value), parseFloat(checkValue))) {
return options.messages[check];
}
}
}

if (options.odd && !(parseInt(value, 10) % 2)) {
return options.messages.odd;
}

if (options.even && parseInt(value, 10) % 2) {
return options.messages.even;
}

return null;
}

length(value = "", options = {}) {
const { length } = value;
const LENGTH_CHECKS = {
is(a, b) {
return a === b;
},
minimum(a, b) {
return a >= b;
},
maximum(a, b) {
return a <= b;
},
};
const blankOptions = {};
blankOptions.message = (() => {
if (options.is) {
return options.messages.is;
} else if (options.minimum) {
return options.messages.minimum;
}
})();

const message = this.presence(value, blankOptions);
if (message) {
if (options.allow_blank === true) {
return null;
}
return message;
}

for (let check in LENGTH_CHECKS) {
const check_function = LENGTH_CHECKS[check];
if (options[check]) {
if (!check_function(length, parseInt(options[check]))) {
return options.messages[check];
}
}
}

return null;
}

exclusion(value = "", options = {}) {
const message = this.presence(value, options);
if (message) {
if (options.allow_blank === true) {
return null;
}
return message;
}

if (options.in) {
let needle;
if (
((needle = value),
Array.from(
Array.from(options.in).map((option) => option.toString())
).includes(needle))
) {
return options.message;
}
}

if (options.range) {
const lower = options.range[0];
const upper = options.range[1];
if (value >= lower && value <= upper) {
return options.message;
}
}

return null;
}

inclusion(value = "", options = {}) {
const message = this.presence(value, options);
if (message) {
if (options.allow_blank === true) {
return null;
}
return message;
}

if (options.in) {
let needle;
if (
((needle = value),
Array.from(
Array.from(options.in).map((option) => option.toString())
).includes(needle))
) {
return null;
}
return options.message;
}

if (options.range) {
const lower = options.range[0];
const upper = options.range[1];
if (value >= lower && value <= upper) {
return null;
}
return options.message;
}
}

confirmation(value = "", options = { confirmation: "" }) {
if (value.toLowerCase() !== options.confirmation.toLowerCase()) {
return options.message;
}
return null;
}

// eslint-disable-next-line no-unused-vars
uniqueness(value = "", options = {}) {
// Impossible to test locally, always return null
return null;
}
}

export default ClientSideValidations;
24 changes: 24 additions & 0 deletions yup/model_validations_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#
# This module uses `client_side_validations` gem to extract
# model validations, so we have the same goals and restrictions
# that they have: https://github.com/DavyJonesLocker/client_side_validations
#
module ModelValidationsService

def self.get_validations(model_name)
model_class = Object.const_get(model_name)
validation_hash = model_class.new.client_side_validation_hash

validation_hash.map do |attr_name, validators|
{
attribute: attr_name.to_s.camelize(:lower),
validators: validators.map do |name, options|
{
name: name,
options: options
}
end
}
end
end
end
45 changes: 45 additions & 0 deletions yup/validateSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import ClientSideValidations from "./ClientSideValidations";

const validation = (value = "", validations = []) => {
const clientSideValidations = new ClientSideValidations();

// Save responses
const responses = [];

// Convert value to string
const strValue = typeof value === "number" ? `${value}` : value;

// Validate each option
validations.forEach(({ name, options }) => {
const parsedOptions = options.map((option) =>
typeof option === "string" ? JSON.parse(option) : option
);
parsedOptions.forEach((options) => {
const result = clientSideValidations[name](strValue, options) || null;
if (result) {
responses.push(result);
}
});
});

if (responses.length) {
// Format response string
let formattedResponse = "";
formattedResponse = "";
responses.forEach((response, i) => {
formattedResponse = i ? formattedResponse + ", " + response : response;
});
formattedResponse =
formattedResponse.charAt(0).toUpperCase() +
formattedResponse.slice(1) +
".";

// Fail validation
return formattedResponse;
} else {
// Pass validation
return "";
}
};

export default validation;
Loading