I need to validate the routine (Chilean ID) that is entered in a form, for this I am using asp.net mvc 5, but I do not know how I can create my own validator for this data.
Can someone help me or guide me on how to create this validator?
I need to validate the routine (Chilean ID) that is entered in a form, for this I am using asp.net mvc 5, but I do not know how I can create my own validator for this data.
Can someone help me or guide me on how to create this validator?
To create a custom data annotation validator, follow these guidelines:
Your class has to inherit from the class System.ComponentModel.DataAnnotations.ValidationAttribute
.
Override the bool IsValid(object value)
method implements the validation logic within it.
Sometimes developers check that the value is not null / empty and returns false. In general, this is an incorrect behavior, because the validator Required
must be verified, which means that the custom validators only have to validate data that is not null, but return the opposite true
(see example). This will make them usable in mandatory and non-mandatory fields.
public class StringLengthRangeAttribute : ValidationAttribute
{
public int Minimum { get; set; }
public int Maximum { get; set; }
public StringLengthRangeAttribute()
{
this.Minimum = 0;
this.Maximum = int.MaxValue;
}
public override bool IsValid(object value)
{
string strValue = value as string;
if (!string.IsNullOrEmpty(strValue))
{
int len = strValue.Length;
return len >= this.Minimum && len <= this.Maximum;
}
return true;
}
}
All properties can be set in the attribute you want to configure. Some examples:
[Required]
[StringLengthRange(Minimum = 10, ErrorMessage = "Debe tener> 10 caracteres.")]
[StringLengthRange(Maximum = 20)]
[Required]
[StringLengthRange(Minimum = 10, Maximum = 20)]
When a particular property is not configured, its value is set in the constructor, so it always has a value. In the previous usage examples, I also deliberately added the validator Required
, so it is in tune with the caution above that I have written.
Then this validator will work on the value of your model that is not necessary, but when it is present it validates it (think of a text field in a web form, that is not mandatory, but if a user enters a value, it must be valid).
For more information:
Source SO: link
Here is this link: Custom Data Annotation Validator Part I: Server Code that you can use ...