Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
Comprobación del validador exprés si la entrada es una de las opciones disponibles

Actualmente tengo un código html como este:

 <!DOCTYPE html> <html> <body> <p>Select an element</p> <form action="/action"> <label for="fruit">Choose a fruit:</label> <select name="fruit" id="fruit"> <option value="Banana">Banana</option> <option value="Apple">Apple</option> <option value="Orange">Orange</option> </select> <br><br> <input type="submit" value="Submit"> </form> </body> </html>

Y en el lado del servidor, quiero verificar con el validador expreso si la fruta en la solicitud de publicación es un plátano, una manzana o una naranja. Este es el código que tengo hasta ahora:

 const{body} = require('express-validator'); const VALIDATORS = { Fruit: [ body('fruit') .exists() .withMessage('Fruit is Requiered') .isString() .withMessage('Fruit must be a String') ] } module.exports = VALIDATORS;

¿Cómo verifico si la cadena enviada por la solicitud POST es una de las frutas requeridas?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Dado que express-validator se basa en validator.js , ya debería estar disponible un método que podría usar para este caso. No es necesario un método de validación personalizado.

Desde los documentos de validator.js , verifique si la cadena está en una matriz de valores permitidos:

 isIn(str, values)

Puede usar esto en la API de cadena de validación, en su caso como:

 body('fruit') .exists() .withMessage('Fruit is Requiered') .isString() .withMessage('Fruit must be a String') .isIn(['Banana', 'Apple', 'Orange']) .withMessage('Fruit does contain invalid value')

Este método también se incluye en los documentos express-validator , aquí https://express-validator.github.io/docs/validation-chain-api.html#not (se usa en el ejemplo para el método not )

over 4 years ago · Santiago Trujillo Report

0

Puede hacerlo a través de la función .custom;

Por ejemplo:

 body('fruit').custom((value, {req}) => { const fruits = ['Orange', 'Banana', 'Apple']; if (!fruits.includes(value)) { throw new Error('Unknown fruit type.'); } return true; })
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!