如何使用Yup结合正则校验字符串中的特殊字符?
Got it, let's break down how to handle this validation scenario with Yup. Your core goal is to make sure user inputs like bank account numbers don't include special characters (like @, #, $) or emojis, and you want to focus on using Yup's regex support—we'll cover that first, then touch on the oneOf method for restricting integers as a bonus.
1. Core Implementation: Regex Validation
The key here is using Yup's matches() method with a regular expression that explicitly allows only the characters you want (and rejects everything else).
Basic Regex for Alphanumeric Inputs
If your bank account allows both letters and numbers, use this regex to block all special characters and emojis:
import * as Yup from 'yup'; const bankValidationSchema = Yup.object().shape({ bankAccount: Yup.string() .required('Bank account number is required') .matches( /^[a-zA-Z0-9]*$/, 'Bank account number cannot contain special characters or emojis' ) });
- The regex
^[a-zA-Z0-9]*$ensures the entire string only contains uppercase/lowercase letters and numbers. Any character outside this set (including @, #, $, emojis, spaces, etc.) will trigger the error message.
For Numeric-Only Accounts
If your bank account should only have numbers, tweak the regex to:
.matches( /^[0-9]*$/, 'Bank account number can only contain digits' )
Blocking Non-ASCII Emojis
If you want an extra layer to exclude all non-ASCII characters (which covers most emojis), use this regex instead:
.matches( /^[\x00-\x7F]*$/, 'Bank account number cannot contain special characters or non-ASCII emojis' )
This regex limits input to only ASCII characters—perfect if you want to avoid any non-standard symbols entirely.
2. Bonus: Restricting to Specific Integers with oneOf
While regex is the right tool for your core requirement, if you ever need to restrict input to a fixed set of integers, Yup's oneOf() method works well. Note that this is best for predefined values, not arbitrary integers (use Yup.number().integer() for that).
Example:
// List of valid bank account integers (for example purposes) const validAccountNumbers = [12345678, 87654321, 11223344]; const validationSchema = Yup.object().shape({ bankAccount: Yup.number() .required('Bank account number is required') .oneOf(validAccountNumbers, 'Invalid bank account number') });
3. Test Scenarios to Verify
Try these inputs to make sure the validation works as expected:
- Valid:
1234567890orABC987XYZ→ Passes - Invalid:
123@456,789#012,456😀789→ Triggers error message
内容的提问来源于stack exchange,提问作者Nitin Kumar

