Ali
Ali

Reputation: 2592

Regular Expression Issue on Model Class

I have a model class with the following property for my country list.

    [Required(ErrorMessage = "Please select a country")]
    [RegularExpression("^(?!----------------$)", ErrorMessage= "Please select a country")]
    public string Country { get; set; }

At the moment when users click on any countries they will get the error message !? I only need to display the error message when users click on ---------------- option only.

enter image description here

I have already tried couple of other expressions but they seem not work at all. also tried this : [RegularExpression("/^(?!----------------)$/" any ideas ?

Upvotes: 1

Views: 43

Answers (1)

J0e3gan
J0e3gan

Reputation: 8938

Use a pattern that matches what is valid of course. Also, do not use opening and closing forward slashes in your pattern.

An easy fix for the pattern you tried is to supplement the negative lookahead with .+:

^(?!----------------).+$

Here is a regex fiddle for the tweaked version of your pattern.

However, I would consider a pattern like the following judging by the countries in your list - and refine it as needed (e.g. for Unicode characters etcetera):

^[A-Z][a-z]+( [A-Z][a-z]+)*( \([A-Z]+\))*$

Here is a regex fiddle for this alternate (starting-point) pattern.

Upvotes: 1

Related Questions