Phone Number Validation MVC

后端 未结 9 1322
轮回少年
轮回少年 2020-12-07 20:51

I am trying to use a regular expression to validate a phone number and return an error when an invalid number or phone number is submitted.

MVC Code

9条回答
  •  温柔的废话
    2020-12-07 21:48

    [DataType(DataType.PhoneNumber)] does not come with any validation logic out of the box.

    According to the docs:

    When you apply the DataTypeAttribute attribute to a data field you must do the following:

    • Issue validation errors as appropriate.

    The [Phone] Attribute inherits from [DataType] and was introduced in .NET Framework 4.5+ and is in .NET Core which does provide it's own flavor of validation logic. So you can use like this:

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

    However, the out-of-the-box validation for Phone numbers is pretty permissive, so you might find yourself wanting to inherit from DataType and implement your own IsValid method or, as others have suggested here, use a regular expression & RegexValidator to constrain input.

    Note: Use caution with Regex against unconstrained input per the best practices as .NET has made the pivot away from regular expressions in their own internal validation logic for phone numbers

提交回复
热议问题