I have created a custom validation attribute to use a regular expression where the expression is stored in a global resource.
public class RegExResourceAttribute : ValidationAttribute, IClientValidatable
{
private string RegexResource;
public RegExResourceAttribute(string regexResource) : base()
{
RegexResource = regexResource;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if (value.GetType() == typeof(string))
{
string waarde = value.ToString();
string resourceWaarde = Global.ResourceManager.GetString(RegexResource);
if (!string.IsNullOrEmpty(waarde))
{
Regex rg = new Regex(resourceWaarde);
if (rg.IsMatch(waarde))
{
return ValidationResult.Success;
}
else
{
string errorText = Global.ResourceManager.GetString(this.ErrorMessageResourceName);
errorText = string.Format(errorText);
return new ValidationResult(errorText);
}
}
}
}
return null;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mcvr = new ModelClientValidationRule();
mcvr.ValidationType = "regexresource";
string errorText = this.ErrorMessage;
if (string.IsNullOrEmpty(errorText))
{
errorText = Global.ResourceManager.GetString(this.ErrorMessageResourceName);
errorText = string.Format(errorText);
}
string resourceWaarde = Global.ResourceManager.GetString(RegexResource);
mcvr.ErrorMessage = string.Format(errorText, (metadata.DisplayName == null ? metadata.PropertyName : metadata.DisplayName));
mcvr.ValidationParameters.Add("regex", resourceWaarde);
List<ModelClientValidationRule> rules = new List<ModelClientValidationRule>();
rules.Add(mcvr);
return rules.AsEnumerable();
}
}
The clientside script part looks like this:
var resource = "";
$.validator.addMethod("rexexresource", function (value, element, params) {
if (value != null && value != '' && resource != null && resource != '') {
var patt = new RegExp(resource);
if (patt.test(value)) {
return true;
}
}
return false;
});
$.validator.unobtrusive.adapters.add('rexexresource', ['value', 'rexex'], function (options) {
options.rules['rexexresource'] = true; // { targetvalue: options.params.value };
options.messages['rexexresource'] = options.message;
resource = options.params.regex;
});
In the html it looks like this:
<input class="input-validation-error form-control invoer" data-val="true" data-val-regexresource="Alleen letters, cijfers, spaties zijn toegestaan. Beginnen met een spatie is niet toegestaan." data-val-regexresource-regex="^(\S(?:[\-0-9a-zA-ZèéíáïëäöüñÈÉÍÁÏËÄÖÜßÑç\s\.\'.?])+)$" data-val-required="Voer uw straatnaam in" id="txtStraat" name="straat" onblur="check_val(this)" oninput="show_label(this)" type="text" value="[][][[]">
So the regular expression code is stored in a resource for fast editting if needed without having to publish the project.
The c# part works fine, but only when the form is submitted. The javascript part is not working. I have this code in a document.ready and the method is added, but nothing is validated when I enter characters that are not in the expression.
The jquery validation script files are loaded in the top of the page and the javascript file with the above javascript code is loaded at the bottom of the page.
What am I doing wrong here?