You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kev/Drawer/DataValidator/Rule/Format/EmailValidationRule.cs

81 lines
2.5 KiB
C#

1 month ago
using System.Data;
using Validation.Core;
namespace Validation.Rule.Format
{
/// <summary>
/// 邮箱格式校验规则
/// </summary>
public class EmailValidationRule : IValidationRule
{
private readonly string columnName;
public string RuleName => $"Email_{columnName}";
public string Description => $"检查列'{columnName}'的邮箱格式";
/// <summary>
/// 构造函数
/// </summary>
/// <param name="columnName">要校验的列</param>
public EmailValidationRule(string columnName)
{
this.columnName = columnName;
}
/// <inheritdoc />
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 (!IsValidEmail(value))
{
result.AddError(rowIndex, $"第{rowIndex + 1}行,列'{columnName}'的邮箱格式不正确: {value}");
}
}
}
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 (!IsValidEmail(value))
{
result.AddError(rowIndex, $"第{rowIndex + 1}行,列'{columnName}'的邮箱格式不正确: {value}");
}
return result;
}
private bool IsValidEmail(string email)
{
return !string.IsNullOrEmpty(email) &&
email.Contains("@") &&
email.Contains(".") &&
email.IndexOf('@') < email.LastIndexOf('.');
}
}
}