📜  ip 验证 .net 核心 - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:49.403000             🧑  作者: Mango

代码示例1
public class IPAddressAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        YourViewModel yourviewmodel = (YourViewModel)validationContext.ObjectInstance;

        const string regexPattern = @"^([\d]{1,3}\.){3}[\d]{1,3}$";
        var regex = new Regex(regexPattern);
        if (string.IsNullOrEmpty(yourviewmodel.IpAddress))
        {
            return new ValidationResult("IP address  is null");
        }
        if (!regex.IsMatch(yourviewmodel.IpAddress )|| yourviewmodel.IpAddress.Split('.').SingleOrDefault(s => int.Parse(s) > 255)!=null)
        return new ValidationResult("Invalid IP Address");


        return ValidationResult.Success;
    }
}

// use
[IPAddressAttribute]
[Display(Name = "IP Address")]
public string IpAddress { get; set; }