MrJD
MrJD

Reputation: 1889

Data Annotation Phone Number Conversion

I want to gracefully convert phone number input from my users into a specific phone number format.

Ie:

Etc, I also want to convert the other direction:

I want to do this to promote readability for the user but retain a strict data type in the database.

Questions

  1. Is using a dataAnnotation in this manner considered bad practice?
  2. How would I actually write the dataAnnotation( /However you would do it)?
    (please include some code)

    Edit: to clarify, i do not want someone to write the extension for me, I would just like an example of key pieces of code and implementation.

Please Note

Upvotes: 0

Views: 4873

Answers (3)

gprasant
gprasant

Reputation: 16023

You can use DataTypeAttribute like so:

[DataType(DataType.PhoneNumber)]
public string PhoneNumber{get; set;}

Upvotes: 0

jessehouwing
jessehouwing

Reputation: 114661

Depending on the UI you're using, you might be able to do this using a:

As parsing and formatting usually happens in the UI layer, I doubt you will find a solution that works at the data/model layer and which will work universally or which can do more than just validation.

In the data annotations namespace, there is a DataType.PhoneNumber which you can attach to your properties. Though you, yourself, remain responsible to do the parsing and the formatting using the appropriate display technology.

Upvotes: 3

Travis J
Travis J

Reputation: 82287

  1. Data annotations and datatype are used for validation, not for converting values. The datatype is mostly used so that the validation knows where to start guessing.

2. That is asking too much for someone to code an extension like that, especially without showing any effort.

Upvotes: 0

Related Questions