我有一个带有ipaddresses的文本字段,但现在允许把ipaddress放在:127或192开头。我有这个:
foreach (var item in lines)
{
if (item.StartsWith("127") || item.StartsWith("192"))
{
foreach (var result in lines)
{
//lines[result].ToString()
result.ToString();
return new ValidationResult("Some Ip Address(ses) are not correct" + "\n" + result.ToString() );
}
// return new ValidationResult("IpAddress cant be saved");
}
if (String.IsNullOrWhiteSpace(IpCondition.IpAddress))
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
IPAddress address;
if (IPAddress.TryParse(item, out address))
continue;
else
return new ValidationResult("IpAddress cant be saved");
}
但问题是,如果你在文本字段中输入:127和192,你只会看到:127而不是192错误的ipaddress。
我现在就这样:
IpConditionSettings IpCondition = validationContext.ObjectInstance as IpConditionSettings;
string[] lines = IpCondition.IpAddress.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
lines = IpCondition.IpAddress.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);
var resultsValidation = new List<ValidationResult>();
foreach (var item in lines)
{
var result = lines.Where(x => x.StartsWith("127") || x.StartsWith("192"));
if (result.Any())
return new ValidationResult("Some Ip Address(ses) are not correct", result);
if (String.IsNullOrWhiteSpace(IpCondition.IpAddress))
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
IPAddress address;
if (IPAddress.TryParse(item, out address))
continue;
else
return new ValidationResult("IpAddress cant be saved");
}
但现在它没有显示错误信息。
如何拥有这件作品:
if (IPAddress.TryParse(item, out address))
continue;
else
return new ValidationResult("IpAddress cant be saved");
错误的IP地址?
答案 0 :(得分:1)
您可以使用linq查询来获取无效地址。
var result = lines.Where(x => x.StartsWith("127") || x.StartsWith("192"));
然后使用ValidationResult(String, IEnumerable<String>)
构造函数返回结果。
if(result.Any())
return new ValidationResult("Some IP-address(es) are not correct.", result);
或者,如果您想在单个字符串中返回它们,可以使用String.Join()
。
if(result.Any())
return new ValidationResult("Some IP-address(es) are not correct.\n" + String.Join(", ", result));