You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.2 KiB
JavaScript

"use strict";
const { validateValue } = require("@validatem/core");
const ValidationError = require("@validatem/error");
const isString = require("@validatem/is-string");
const required = require("@validatem/required");
const dynamic = require("./");
let formRules = dynamic((formData) => {
return {
username: [ required, isString ],
password: [ required, isString ],
// NOTE: Below, we are generating a rule that references the *actual* form data that was passed into `validateValue`.
passwordAgain: [ required, (value) => {
// We specify a custom validation function here, but we could have also called eg. @validatem/one-of with some of the values from the input data.
if (value !== formData.password) {
throw new ValidationError(`Passwords must match`);
}
} ]
};
});
let formA = {
username: "foo",
password: "bar",
passwordAgain: "bar"
};
console.log(validateValue(formA, [ formRules ])); // { username: 'foo', password: 'bar', passwordAgain: 'bar' }
let formB = {
username: "foo",
password: "bar",
passwordAgain: "not bar"
};
console.log(validateValue(formB, [ formRules ])); /*
AggregrateValidationError: One or more validation errors occurred:
- At passwordAgain: Passwords must match
*/