Taio
Taio

Reputation: 3734

Regex for a name and number 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

Upvotes: 21

Views: 50332

Answers (7)

Ahmad Raza
Ahmad Raza

Reputation: 1

 validator: (value) {
                  var namevalid =
                      RegExp(r'^[A-Z][a-z]*$').hasMatch(value!);
                  if (value!.isEmpty) {
                    return "Enter First Name";
                  }
                  if (!namevalid) {
                    return "Your name is not Valid";
                  }
                  return null;
                },

Upvotes: 0

Evgeny
Evgeny

Reputation: 139

//\$ <- helps to exclude *, -, " and other characters
// so nameInputRegex.hasMatch.("alex-") will return false

get nameInputRegex => "^[a-zA-Z0-9]{2,$maxNameLength}\$";

Upvotes: 0

mezoni
mezoni

Reputation: 11210

The following code should also work.
The parser is a constant expression, it is fast and does not consume much memory.

import 'package:parser_combinator/parser/alpha1.dart';
import 'package:parser_combinator/parser/digit1.dart';
import 'package:parser_combinator/parser/eof.dart';
import 'package:parser_combinator/parser/many1.dart';
import 'package:parser_combinator/parser/predicate.dart';
import 'package:parser_combinator/parser/skip_while.dart';
import 'package:parser_combinator/parser/terminated.dart';
import 'package:parser_combinator/parsing.dart';

void main(List<String> args) {
  const name = Terminated(
    Many1(
      Terminated(Alpha1(), SkipWhile(isWhitespace)),
    ),
    Eof(),
  );

  const number = Terminated(Digit1(), Eof());

  final input1 = 'John  Snow '.trim();
  final r1 = tryParse(name.parse, input1).result;
  if (r1 != null) {
    final fullName = r1.value;
    print('Name is valid: $input1');
    print('First name: ${fullName.first}');
    if (fullName.length > 1) {
      print('Second name: ${fullName[1]}');
    }
  }

  final input2 = ' 123 '.trim();
  final r2 = tryParse(number.parse, input2).result;
  if (r2 != null) {
    print('Number is valid: $input2');
  }
}

Output:

Name is valid: John  Snow
First name: John
Second name: Snow
Number is valid: 123

Upvotes: 0

Rushikesh Tokapure
Rushikesh Tokapure

Reputation: 139

this worked for me

void main() {
  RegExp nameRegex = RegExp(r"^[a-zA-Z]+$");
  RegExp numberRegex = RegExp(r"^\d+$");
  print(nameRegex.hasMatch("Ggggg"));
  print(numberRegex.hasMatch("999"));
}

Upvotes: 3

Duan Nguyen
Duan Nguyen

Reputation: 468

Base on this answer and this information:

\p{L} or \p{Letter}: any kind of letter from any language.

Reference: http://www.regular-expressions.info/unicode.html

The regex for a name validation:

RegExp(r"^[\p{L} ,.'-]*$",
      caseSensitive: false, unicode: true, dotAll: true)
  .hasMatch(my_name)

Upvotes: 8

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

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)

Upvotes: 17

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657416

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');

Upvotes: 25

Related Questions