0

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?

update (2021-04-20): enter image description here

Eric
  • 105
  • 1
  • 9
  • Try adding some JavaScript "alert" statements to determine what code is being executed and that the variable values are as expected. Doing this can show what is wrong. Once the problem is corrected, then comment out the "alert" statements. – JohnH Apr 16 '21 at 16:08
  • 1
    @JohnH - https://stackoverflow.com/questions/8203473/why-is-console-log-considered-better-than-alert – Sparky Apr 16 '21 at 20:04
  • Anyone have an idea? pls? – Eric Apr 22 '21 at 09:01
  • I still haven't found a solution for this. Is there anyone that can help me with this? – Eric May 04 '21 at 09:49

0 Answers0