如何用Vuelidate实现逗号分隔多邮箱列表的表单验证?
Got it, let's get your comma-separated email list validated properly with Vuelidate. Here's a straightforward implementation that builds on your existing setup:
Step 1: Create a Custom Multi-Email Validator
Vuelidate's built-in email validator only checks single addresses, so we'll craft a custom one that splits the input and validates each entry individually:
import { email as emailValidator, required } from 'vuelidate/lib/validators' // Custom validator for comma-separated email lists const multiEmail = value => { if (!value) return true // Skip validation if empty (keep this if the field isn't mandatory) // Split input by commas, trim whitespace from each entry, filter out empty strings const emailList = value.split(',').map(email => email.trim()).filter(email => email.length > 0) // Validate every entry against Vuelidate's standard email rule return emailList.every(email => emailValidator(email)) }
Step 2: Update Your Vuelidate Validation Rules
Swap out the single email rule with our new multiEmail validator in your component's validation schema:
export default { data() { return { newParcel: { onSiteContactEmail: '' } } }, validations: { newParcel: { onSiteContactEmail: { required, // Keep this line if the field is mandatory multiEmail // Our custom multi-email validator } } } }
Step 3: Adjust Your Template for Clear Feedback
Update your form template to handle the multi-email validation state, and add specific error messages to guide users:
<div class="form-group" :class="{ 'has-error': $v.newParcel.onSiteContactEmail.$error }"> <label for="onSiteContactEmail">OnSite Contact Email</label> <input type="text" name="onSiteContactEmail" id="onSiteContactEmail" class="form-control" v-model="newParcel.onSiteContactEmail" @input="$v.newParcel.onSiteContactEmail.$touch" maxlength="255" placeholder="Example: john@example.com, jane@example.com" > <span v-show="$v.newParcel.onSiteContactEmail.$error"> <span v-if="!$v.newParcel.onSiteContactEmail.required">This field is required.</span> <span v-else>Please enter valid comma-separated email addresses.</span> </span> </div>
Bonus: Optional Enhancements
- Auto-Clean Input: Add a watcher to automatically tidy up the user's input (remove extra spaces around commas):
watch: { 'newParcel.onSiteContactEmail'(val) { this.newParcel.onSiteContactEmail = val.replace(/\s*,\s*/g, ',').trim() } } - Target Invalid Emails: If you want to highlight exactly which email is invalid, you can extend the validator with Vuelidate's
withParamsutility to return specific error details, though that adds a bit more complexity.
This setup ensures every email in the comma-separated list passes Vuelidate's standard email validation, while fitting seamlessly into your existing form structure.
内容的提问来源于stack exchange,提问作者Matt Larsuma

