slickgrid validate column with regex

2020-02-29 10:41发布

问题:

There is a simple sample with column validation:

    function requiredFieldValidator(value) {
      if (value == null || value == undefined || !value.length) {
        return {valid: false, msg: "This is a required field"};
      } else {
        return {valid: true, msg: null};
      }
    }

and to validate column it is just needed to put this option: validator: requiredFieldValidator

But how can I use regex function if I need to pass extra parameter - regex string.

回答1:

By default, you cannot pass more parameters into the validator method, however you can easily edit the source to allow it.

in slick.editors.js look for:

this.validate = function () {
  if (args.column.validator) {
    var validationResults = args.column.validator($input.val());
    if (!validationResults.valid) {
      return validationResults;
    }
  }

  return {
    valid: true,
    msg: null
  };
};

change: var validationResults = args.column.validator($input.val());

to: var validationResults = args.column.validator($input.val(), $input);

this will change your validator method signature to something like:

function requiredFieldValidator(value, input)

With that, you can get whatever attributes you want out of input with input.attr('validation-expression') or input.data... or whatever.



回答2:

The best way to approach this, in my view anyways, is to code your own editor which you'll add into slick.editor.js as another new custom editor. This file is made for that too. I did implement the regex test and it works great.

Here's my new editor which is not only working for Regex but also for various condition types, for example an option of min:2 would required a minimum number of 2, while a minLength:2 would required the input to be a String of at least 2 chars, etc... Now for the one you're really looking for, that would be in my code definition the pattern type. So basically, you'll have to include this code inside the slick.editor.js :

ConditionalCellEditor : function(args) {            
    var $input;
                var defaultValue;
                var scope = this;
    var condObj = null;

                this.init = function() {
                        $input = $("<INPUT type='text' class='editor-text' />")
                                .appendTo(args.container)
                                .bind("keydown.nav", function(e) {
                                        if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
                                                e.stopImmediatePropagation();
                                        }
                                })
                                .focus()
                                .select();
                };

                this.destroy = function() {
                        $input.remove();
                };

                this.focus = function() {
                        $input.focus();
                };

                this.getValue = function() {
                        return $input.val();
                };

                this.setValue = function(val) {
                        $input.val(val);
                };

                this.loadValue = function(item) {
                        defaultValue = item[args.column.field] || "";
                        $input.val(defaultValue);
                        $input[0].defaultValue = defaultValue;
                        $input.select();
                };

                this.serializeValue = function() {
                        return $input.val();
                };

                this.applyValue = function(item,state) {
                        item[args.column.field] = state;
                };

                this.isValueChanged = function() {
                        return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
                };

                this.validate = function() {
        var condObj = args.column.editorOptions;
        var returnMsg = null;
        var returnValid = true;

        if(typeof condObj.min != 'undefined') {

            if( parseFloat($input.val()) < parseFloat(condObj.min) ) {
                returnMsg = "Value should not be less then "+condObj.min;
                returnValid = false;
            }
        }
        if(typeof condObj.max != 'undefined') {
            if( parseFloat($input.val()) > parseFloat(condObj.max) ) {
                returnMsg = "Value should not be over "+condObj.max;
                returnValid = false;
            }
        }
        if(typeof condObj.minLength != 'undefined') {

            if($input.val().length < condObj.minLength) {
                returnMsg = "Value length should not be less then "+condObj.minLength;
                returnValid = false;
            }
        }
        if(typeof condObj.maxLength != 'undefined') {
            if($input.val().length > condObj.maxLength) {
                returnMsg = "Value length should not be over "+condObj.maxLength;
                returnValid = false;
            }
        }
        if(typeof condObj.pattern != 'undefined') {
            if( condObj.pattern.test($input.val()) != true ) {
                returnMsg = (condObj.msg) ? condObj.msg : "Value is invalid following a regular expression pattern";
                returnValid = false;
            }
        }               
        if(typeof condObj.required != 'undefined') {
            if($input.val().length == "" && condObj.required) {
                returnMsg = "Required field, please provide a value";
                returnValid = false;
            }
        }

        // Now let's return our boolean results and message if invalid
        return {
            valid: returnValid,
            msg: returnMsg
        }
                };

                this.init();
},

Then inside my SlickGrid column definition I'm calling that new editor which I defined and passing some options which I decided to pass into an editorOptions as an Object and that gives me more flexibility to add any options I want, pattern, msg, minLength, etc... all at one. My example is for an email regex pattern validation.

columns1 = [
...
{id:"email", field:"email", name:"Em@il", width:145, editor:ConditionalCellEditor, editorOptions:{pattern:/^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/, msg:"Must be a valid email"} },
...];

And voilà, works like a charm!!! I'm barely using the editor:TextCellEditor anymore, since my new ConditionalCellEditor editor gives me a lot more flexibility. Hope it helps and let me know how it goes...



回答3:

In order to extend the answer of @mike-gwilt, you can use the cellAttrs column options to specify (in your column definition) the regular expressions and the message to report, like this:

... { id: "columnId", name: "columnName", validator: RegexValidator, cellAttrs: {"reg":"^\\d{1,2}$", "msg": "The value should be a number of two digits."} ...

Then the html generated looks something like this:

<div class="slick-cell l9 r9 active editable selected" reg="^\d{1,3}$" msg="The value should be a number of two digits."><input type="text" class="editor-text" value=""></div>

Finally, as you can access the input element inside your validation function, define it like this:

 function RegexValidator(value, input) {
    var msg = input.parent().attr('msg');
    var reg = new RegExp(input.parent().attr('reg'));
    if (!reg.exec(value)) {
        return { valid: false, msg: msg};
    } else {
        return { valid: true, msg: null };
    }
 }


回答4:

This was very helpful. I am creating different input types for every type of possible entry - email, phone, zip and so forth. To do this with JSON, you have to modify your slick.grid.js file to evaluate the entries to make them an object call.

if (d) {
  if(m.formatter){
    m.formatter=eval(m.formatter)
    } // make it an object call instead of string

if(m.editor) {
    m.editor=eval(m.editor)
    }

if(m.editorOptions) {
    m.editorOptions=eval(m.editorOptions)
    }

    }

Make your JSON columns have this update:

\"editor\": \"Slick.Editors.Conditional\", 
\"editorOptions\": 
   {\"pattern\":\"email\", \"msg\":\"Must be a valid email\",  \"required\":\"1\"}

Make youre slick.editors.js look like this:

(function ($) {
 $.extend(true, window, {
  "Slick": {
  "Editors": {
  "Conditional": Conditional, 

inside -> function Conditional(args){

if(typeof condObj.pattern != 'undefined') {
    if(condObj.pattern=='email'){
        pattern=/^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/;
        val=$input.val();
      if(pattern.test(val) != true && val!='')  {
           returnMsg = (condObj.msg) ? condObj.msg : "Value is invalid";
           returnValid = false;
      }
 } 
}
if(!returnValid){
   alert(returnMsg)
}