【发布时间】:2019-04-14 16:55:52
【问题描述】:
我想创建自己的验证器,用于检查注册表中的 PESEL 是否正确。
标准:
- 如果有错误,该字段不能为空。
- 数值为11位数字,否则报错。
- 如果验证函数不检查 PESEL 计算方法,则返回错误。
PESEL的计算原理:
我们将通过 3 个简单的步骤在下面描述如何计算支票 PESEL 编号中的数字。例如,我们将使用数字 0207080362.
将 PESEL 编号中的每个数字乘以适当的权重: 1-3-7-9-1-3-7-9-1-3。 0 * 1 = 0 2 * 3 = 6 0 * 7 = 0 7 * 9 = 63 0 * 1 = 0 8 * 3 = 24 0 * 7 = 0 3 * 9 = 27 6 * 1 = 6 2 * 3 = 6
将获得的结果添加到自己。请注意,如果您收到 乘法过程中的两位数,只加最后一个 数字(例如,加 3 而不是 63)。 0 + 6 + 0 + 3 + 0 + 4 + 0 + 7 +6 + 6 = 32 从 10 中减去结果。注意:如果您收到 加法时两位数,只减去最后一位数 (例如,减去 2 而不是 32)。你得到的数字是一张支票 数字。 10 - 2 = 8 个完整的 PESEL 编号:02070803628
实际上它对我不起作用,我总是在我的表单中说这样的话:
怎么了?
空值输入:
- 输入错误的数字:
- 输入正确的数字:
代码:
public class ValidatePesel : ValidationAttribute
{
int result_status = 0;
public string errorLenght = "Długość numeru PESEL musi zawierać 11 cyfr";
public string errorPesel = "numer PESEL jest niepoprawny";
public string errorType = "Podana wartość nie jest numerem PESEL";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string pesel = value.ToString();
bool result_pesel = int.TryParse(pesel, out result_status);
// Verification of PESEL correctness
if (result_pesel)
{
if (pesel.Length == 11) // Check if the given length is correct
{
int[] weight = { 1, 3, 7, 9, 1, 3, 7, 9, 1, 3 }; // weights to calculate
int sum = 0;
int controlNum = int.Parse(pesel.Substring(10, 11)); // to the control value we assign the last number, the first one is the last one is 11 because 10 is the number 11 and then the length of the data
for (int i = 0; i < weight.Length; i++)
{
sum += int.Parse(pesel.Substring(i, i + 1)) * weight[i]; // we multiply each number by weight
}
sum = sum % 10; // we return the value of the checksum
if (10 - sum == controlNum)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(errorPesel);
}
}
else
return new ValidationResult(errorLenght);
}
else
return new ValidationResult(errorType);
}
}
模型中实现的代码:
namespace Clinic. Models
{
public class RegistrationForPatient: ValidatePesel
{
public int Id {get; set; }
// We create validation of user data, if the user leaves an empty field, it returns a message from the RequiredAttribute function
[Required]
[ValidatePesel]
[Display (Name = "Pesel")]
public string PESEL {get; set; }
// Email validation, required field
[Required]
[Display (Name = "E-mail")]
[EmailAddress]
public string Email {get; set; }
[Required (ErrorMessage = "Password field, can not be empty")]
[Display (Name = "Password")]
public string Password {get; set; }
[Required (ErrorMessage = "Please repeat the password")]
[Display (Name = "Repeat password")]
public string RepeatPassword {get; set; }
}
}
【问题讨论】:
标签: c# asp.net-mvc validation