How can I write the validation using data annotation in writing telephone number such as "094-4567" or mobile number such as "09129705678" etc.?
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace PhoneBook.Models
{
public class Contact
{
[Required(ErrorMessage="Telephone Number Required")
[?]
public string Telephone Number {get; set;}
}
}
I really don't know what to do...
Phone Number Validation in ASP.NET Core In net core, validation rules are defined in the model. Phone number validation uses the DataAnnotations namespace, which has two validation attributes: DataType and Phone. You should use the DataType in your model class if your MobilePhone field is of a simple type.
The DataAnnotations namespace provides two ways of validating a telephone numbers as a data type, enumeration and derived class. Use the enumeration method when your phone number field is a simple type and use the derived class when the field is an object type.
You can use regular expression attribute like so:
namespace PhoneBook.Models
{
public class Contact
{
[Required(ErrorMessage="Telephone Number Required")
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone format is not valid.")]
public string Telephone Number {get; set;}
}
}
It will match numbers like: 0123456789, 012-345-6789, (012)-345-6789 etc.
You can learn more about this expression here: How to use Regular expression for validating Phone Numbers
Try this:
[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]
Try for simple regular expression for Mobile No
[Required (ErrorMessage="Required")]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
public string Mobile { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With