|
|
|
|
|
using System.Data;
|
|
|
|
|
|
using Validation.Core;
|
|
|
|
|
|
|
|
|
|
|
|
namespace Validation.Rule.Format
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 长度校验
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class LengthValidationRule : IValidationRule
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly string columnName;
|
|
|
|
|
|
private readonly int minLength;
|
|
|
|
|
|
private readonly int maxLength;
|
|
|
|
|
|
|
|
|
|
|
|
public string RuleName => $"Length_{columnName}";
|
|
|
|
|
|
public string Description => $"检查列'{columnName}'的字符串长度[{minLength}, {maxLength}]";
|
|
|
|
|
|
|
|
|
|
|
|
public LengthValidationRule(string columnName, int minLength, int maxLength)
|
|
|
|
|
|
{
|
|
|
|
|
|
this.columnName = columnName;
|
|
|
|
|
|
this.minLength = minLength;
|
|
|
|
|
|
this.maxLength = maxLength;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public ValidationResult Validate(DataTable dataTable)
|
|
|
|
|
|
{
|
|
|
|
|
|
var result = new ValidationResult { IsValid = true };
|
|
|
|
|
|
|
|
|
|
|
|
if (!dataTable.Columns.Contains(columnName))
|
|
|
|
|
|
return result;
|
|
|
|
|
|
|
|
|
|
|
|
foreach (DataRow row in dataTable.Rows)
|
|
|
|
|
|
{
|
|
|
|
|
|
int rowIndex = dataTable.Rows.IndexOf(row);
|
|
|
|
|
|
|
|
|
|
|
|
if (!row.IsNull(columnName))
|
|
|
|
|
|
{
|
|
|
|
|
|
var value = row[columnName]?.ToString() ?? string.Empty;
|
|
|
|
|
|
if (value.Length < minLength || value.Length > maxLength)
|
|
|
|
|
|
{
|
|
|
|
|
|
result.AddError(rowIndex, $"第{rowIndex + 1}行,列'{columnName}'的长度{value.Length}超出范围[{minLength}, {maxLength}]");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
|
|
public ValidationResult Validate(string[] headers, int rowIndex, object[] values)
|
|
|
|
|
|
{
|
|
|
|
|
|
var result = new ValidationResult { IsValid = true };
|
|
|
|
|
|
|
|
|
|
|
|
// 查找列索引
|
|
|
|
|
|
int columnIndex = Array.IndexOf(headers, columnName);
|
|
|
|
|
|
|
|
|
|
|
|
// 如果找不到列或值为空,则直接返回
|
|
|
|
|
|
if (columnIndex < 0 || columnIndex >= values.Length || values[columnIndex] == null || values[columnIndex] == DBNull.Value)
|
|
|
|
|
|
{
|
|
|
|
|
|
return result;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
var value = values[columnIndex]?.ToString() ?? string.Empty;
|
|
|
|
|
|
if (value.Length < minLength || value.Length > maxLength)
|
|
|
|
|
|
{
|
|
|
|
|
|
result.AddError(rowIndex, $"第{rowIndex + 1}行,列'{columnName}'的长度{value.Length}超出范围[{minLength}, {maxLength}]");
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|