I need to validate a form that a user provides their name and a number. I have a regex that is supposed to make sure the name contains only letters and nothing else and also for the number input i need to make sure only numbers are in the field. The code I have looks like
 validator: (value) => value.isEmpty
                        ? 'Enter Your Name'
                        : RegExp(
                                '!@#<>?":_``~;[]\|=-+)(*&^%1234567890')
                            ? 'Enter a Valid Name'
                            : null,
can i get a regex expression that validates a name in such a way if any special character or number is inputted it becomes wrong meaning only letters are valid and another that validates a number in such a way if an alphabetical letter or any special character is inputted it becomes wrong meaning only the input of a number is valid
Since regular expressions work with text, a regular expression engine treats 0 as a single character, and 255 as three characters. To match all characters from 0 to 255, we'll need a regex that matches between one and three characters. The regex [0-9] matches single-digit numbers 0 to 9.
(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.
It seems to me you want
RegExp(r'[!@#<>?":_`~;[\]\\|=+)(*&^%0-9-]').hasMatch(value)
Note that you need to use a raw string literal, put - at the end and escape ] and \ chars inside the resulting character class, then check if there is a match with .hasMatch(value). Notre also that [0123456789] is equal to [0-9].
As for the second pattern, you can remove the digit range from the regex (as you need to allow it) and add a \s pattern (\s matches any whitespace char) to disallow whitespace in the input:
RegExp(r'[!@#<>?":_`~;[\]\\|=+)(*&^%\s-]').hasMatch(value)
                        Create a static final field for the RegExp to avoid creating a new instance every time a value is checked. Creating a RegExp is expensive.
static final RegExp nameRegExp = RegExp('[a-zA-Z]'); 
    // or RegExp(r'\p{L}'); // see https://stackoverflow.com/questions/3617797/regex-to-match-only-letters 
static final RegExp numberRegExp = RegExp(r'\d');
Then use it like
validator: (value) => value.isEmpty 
    ? 'Enter Your Name'
    : (nameRegExp.hasMatch(value) 
        ? null 
        : 'Enter a Valid Name');
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With