Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for a name and number dart

Tags:

regex

dart

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

like image 492
Taio Avatar asked Aug 24 '18 13:08

Taio


People also ask

Can you use regex with numbers?

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.

What does (? I do in regex?

(? i) makes the regex case insensitive. (? c) makes the regex case sensitive.


2 Answers

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)
like image 143
Wiktor Stribiżew Avatar answered Sep 22 '22 06:09

Wiktor Stribiżew


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');
like image 45
Günter Zöchbauer Avatar answered Sep 24 '22 06:09

Günter Zöchbauer