'How do I access another field's value in Joi validation?
How do I access another field value while I am validating a field?
export const validation = {
body: Joi.object({
name: Joi.string()
.required()
.min(2)
.max(20)
email: Joi
.string()
.required()
.email()
.pattern(new Regex()) // access value name here
.when('name', {
is: Joi.required(),
then: // access value of name here
}),
}),
}
In this case, I want to access the name field value in email field validation.
Solution 1:[1]
You can use the custom function to access the values of an object in the schema
export const validation = {
body: Joi.object({
name: Joi.string()
.required()
.min(2)
.max(20)
email: Joi
.string()
.required()
.email()
}).custom((user, helpers) => {
const { email, name} = user;
if (your regex validation on email) {
// if email validation failed
return helpers.message({
custom: `invalid email`
});
}
if (email !== `${name}@example.com`) {
// if name validation failed
return helpers.message({
custom: `email must be ${name}@example.com`
});
}
return user;
}),
}),
}
Solution 2:[2]
Not sure what you want to do with it but here is a click handler using the classes btn and btn__add_to_cart that are a div.
I also added a form submit handler for the closest form that was clicked.
let submitEvent = new CustomEvent("submit", {
"bubbles": true,
"cancelable": true
});
function logSubmit(event) {
console.log(`Form Submitted! Time stamp: ${event.timeStamp}`);
let button = event.currentTarget.querySelectorAll('input')[0];
console.log(`Form button ID: ${button.id}`);
event.preventDefault();
}
var evt = new CustomEvent("submit", {
"bubbles": true,
"cancelable": true
});
let allforms = document.querySelectorAll('form.add_to_cart');
Array.from(allforms).forEach(function(element) {
element.addEventListener('submit', logSubmit);
});
function clickedMe(event) {
console.log(event.currentTarget === this) // logs `true`
let closestForm = event.currentTarget.closest('form.add_to_cart');
console.log("My Classes:", this.className);
closestForm.dispatchEvent(submitEvent);
}
const clickableButtons = document.querySelectorAll(`div.btn.btn__add_to_cart`);
console.log(clickableButtons.length);
Array.from(clickableButtons).forEach(function(element) {
element.addEventListener('click', clickedMe, false);
});
<form class="add_to_cart">
<div class="btn btn__add_to_cart">Add To Cart</div>
<input type="hidden" id="some_product_id">
</form>
<form class="add_to_cart">
<div class="btn btn__add_to_cart">Add To Cart 2</div>
<input type="hidden" id="some_product_id2">
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aman |
| Solution 2 | Mark Schultheiss |
