如何验证电话号码?

use*_*351 4 c# asp.net-mvc

我正在使用 MVC,我想验证电话 否

我写了这个类:

public class StduentValidator : AbstractValidator<graduandModel>
{
    public StduentValidator(ILocalizationService localizationService)
    {
        RuleFor(x => x.phone).NotEmpty().WithMessage(localizationService.GetResource("Hire.HireItem.Fields.phone.Required"));
    }
}
Run Code Online (Sandbox Code Playgroud)

如何验证此类中的电话号码?

我可以使用以下吗?

RuleFor(x => x.phone).SetValidator(....)
Run Code Online (Sandbox Code Playgroud)

如果是这样,我该如何使用它??

小智 9

下面的代码示例使用流畅的验证进行电话号码验证

  class StudentCommandValidation :  AbstractValidator<StudentCommand>
{
    public StudentCommandValidation()
    {
        RuleFor(p => p.PhoneNumber)
       .NotEmpty()
       .NotNull().WithMessage("Phone Number is required.")
       .MinimumLength(10).WithMessage("PhoneNumber must not be less than 10 characters.")
       .MaximumLength(20).WithMessage("PhoneNumber must not exceed 50 characters.")
       .Matches(new Regex(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}")).WithMessage("PhoneNumber not valid");
    }
}
Run Code Online (Sandbox Code Playgroud)


Yan*_*eau 5

您是否考虑过在模型中使用DataAnnotations

像这样的东西:

[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
public string PhoneNumber { get; set; }
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用正则表达式:

[DisplayName("Phone number")]
[Required(ErrorMessage = "Phone number is required")]
[RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Invalid phone number")]
Run Code Online (Sandbox Code Playgroud)