tickwave
tickwave

Reputation: 3455

Regex for Numeric only or Empty

So I have this regex validation for MVC. It only allows numeric but it also prevent empty field. I want it to only allows numeric but also allows empty field. Any help will be appreciated

[RegularExpression("[0-9]*\\.?[0-9]+", ErrorMessage = "Must be number")]
[RequiredIfEmpty("Phone", ErrorMessage = "Required")]
public string MobilePhone { get; set; }

Upvotes: 0

Views: 63

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

This block in the end

...[0-9]+

requires at least one digit to be presented.

You can capture the whole fraction part with point to ?.

Try this one:

[0-9]*(\.[0-9]+)?    

Note that \ will become escaped \\ in C#.

Upvotes: 2

Related Questions