How to use the ref function from joi

Find comprehensive JavaScript joi.ref code examples handpicked from public code repositorys.

joi.ref is a function that creates a reference to another value in a Joi schema, allowing for more flexible validation rules.

63
64
65
66
67
68
69
70
71
72
user_id,
// 使用 password 这个规则,验证 req.body.oldPwd 的值
old_password: password,
// 使用 joi.not(joi.ref('oldPwd')).concat(password) 规则,验证 req.body.newPwd 的值
// 解读:
// 1. joi.ref('oldPwd') 表示 newPwd 的值必须和 oldPwd 的值保持一致
// 2. joi.not(joi.ref('oldPwd')) 表示 newPwd 的值不能等于 oldPwd 的值
// 3. .concat() 用于合并 joi.not(joi.ref('oldPwd')) 和 password 这两条验证规则
password: joi.not(joi.ref('old_password')).concat(password),
repassword: joi.ref('password')
fork icon1
star icon2
watch icon1

72
73
74
75
76
77
78
79
80
81
82
    .lowercase(),
  password: Joi.string()
    .pattern(new RegExp("^[a-zA-Z0-9]{3,30}$"))
    .min(8)
    .required(),
  confirmPassword: Joi.ref("password"),
  role: Joi.string().valid("guest", "admin").default("guest"),
});


const User = mongoose.model("User", userSchema);
fork icon0
star icon5
watch icon1

How does joi.ref work?

joi.ref is a method in the Joi validation library that allows you to reference other keys in the schema or the parent object and use their values for validation purposes. It returns a reference object that can be used as a schema property value. When the schema is validated, the value of the referenced key is retrieved and used to validate the current property.

20
21
22
23
24
25
26
27
28
29
30
31
32
});


const resetPasswordSchema = Joi.object({
  password: Joi.string().required(),


  password_confirmation: Joi.ref('password'),
});


const signinSchema = Joi.object({
  user: Joi.string().required(),
fork icon0
star icon0
watch icon1

139
140
141
142
143
144
145
146
147
148
149
150
151


  password: Joi.string().min(8).optional(),
  confirmPassword: Joi.string().min(8).optional(),
  token: Joi.string().optional(),


  //  repeat_password: Joi.ref('password'),


  // phone: Joi.string().length(10)
});

fork icon0
star icon0
watch icon1

+ 8 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const Joi = require("joi");

const schema = Joi.object({
  password: Joi.string().min(8).required(),
  passwordConfirmation: Joi.string().valid(Joi.ref("password")).required(),
});

const data = {
  password: "password123",
  passwordConfirmation: "password123",
};

const { error, value } = schema.validate(data);
if (error) {
  console.log(error.message);
} else {
  console.log(value);
}

In this example, Joi.ref('password') is used to ensure that the value of passwordConfirmation matches the value of password. If they don't match, a validation error is thrown.

615
616
617
618
619
620
621
622
623
624
625
626
        waypoints: Joi.array().items(waypointSchema),
      });
~~~~~~~~~~~~~~~~


(!) O trecho pointSchema.invalid(Joi.ref('startingAddress')) que utiliza as validações já definidas em pointSchema e acrescenta
uma nova validação, através da função Joi.ref(), para comparar o valor deste atributo com o atributo startingAddress e se forem
iguais o schema retorna uma mensagem de erro que informa que o valor do atributo endingAddress é inválido.


--> Validando de fato:

fork icon0
star icon0
watch icon1

120
121
122
123
124
125
126
127
128
129
130
  meta: Joi.any()
};


function condition(fun, then, otherwise) {
  return Joi.alternatives().conditional(
    Joi.ref('.'), {
      is: Joi.custom((value, helper) => (fun(value) ? value : helper.message({}))),
      then,
      otherwise
    }
fork icon0
star icon0
watch icon149

+ 14 other calls in file

71
72
73
74
75
76
77
78
79
80
//valid and ref
pwd: Joi.string().min(6).required(),
cpwd: Joi.string().valid(Joi.ref('pwd')).required(),
// cpwd:Joi.ref('pwd'),

//I want to validate object using Joi which inovle use of Joi.ref() with multiplication operation.
k: Joi.number().integer(),
p: Joi.number().integer().min(1).max(Joi.ref('k', {
    adjust: (value) => value * 2
})).error(new Error('positive number dal mere bhai')),
fork icon0
star icon0
watch icon0

+ 5 other calls in file

15
16
17
18
19
20
21
22
23
24
    .required(),

password: Joi.string()
    .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),

repeat_password: Joi.ref('password'),

access_token: [
    Joi.string(),
    Joi.number()
fork icon0
star icon0
watch icon176

+ 3 other calls in file

113
114
115
116
117
118
119
120
121
122
Note that references can only be used where explicitly supported such as in `valid()` or `invalid()` rules. If upwards
(parents) references are needed, use [`object.assert()`](#objectassertref-schema-message).

```js
const schema = Joi.object().keys({
    a: Joi.ref('b.c'),
    b: {
        c: Joi.any()
    },
    c: Joi.ref('$x')
fork icon0
star icon0
watch icon0

+ 5 other calls in file