以下是使用Adonis.js来验证邮件数组的解决方法的代码示例:
npm install @adonisjs/validator
app/Rules/ArrayEmail.js
:'use strict'
const { rule } = require('@adonisjs/validator/build/src/Validator/helpers')
class ArrayEmail {
/**
* Indicates whether array of emails is valid or not.
* @param {Array} emails
* @param {String} field
* @param {Object} message
* @param {Object} args
*/
async validate (emails, field, message, args) {
const emailRegex = /^[\w-]+(\.[\w-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,})$/
if (!Array.isArray(emails)) {
return false
}
for (const email of emails) {
if (!email.match(emailRegex)) {
return false
}
}
return true
}
/**
* Custom error message for validation failure.
* @param {String} field
* @param {Object} args
* @param {String} message
*/
async message (field, args, message) {
return message || `Invalid email address in ${field}`
}
}
module.exports = ArrayEmail
app/Validators/Validator.js
中注册自定义规则:'use strict'
const { ServiceProvider } = require('@adonisjs/fold')
class ValidatorProvider extends ServiceProvider {
boot () {
const Validator = use('Validator')
const ArrayEmail = require('../Rules/ArrayEmail')
Validator.extend('arrayEmail', ArrayEmail.validate, ArrayEmail.message)
}
}
module.exports = ValidatorProvider
'use strict'
const { validate } = use('Validator')
class UserController {
async store ({ request, response }) {
const rules = {
emails: 'required|arrayEmail'
}
const validation = await validate(request.all(), rules)
if (validation.fails()) {
return response.status(400).send(validation.messages())
}
// 继续处理业务逻辑...
}
}
module.exports = UserController
以上代码示例将验证请求中的 emails
字段,确保它是一个有效的邮件地址数组。如果验证失败,将返回一个包含错误消息的响应。