Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
Clear All
new posts

    Small contribution - isNotOneOf validator (inverse of isOneOf validator)

    I needed the opposite of the isOneOf validator (actually I use it quite often in the current project). I decided to code this as a custom validator and register it globally. Then I thought someone else might need the same functionality so I am making my small contribution to this great framework below:

    I borrowed the code from ISC_Forms.js and updated the documentation to match. I haven't changed the default error message since the current string reads 'Not a valid option' and that is fine for me.

    Code:
    // Tests whether the value for this field matches any value from an arbitrary
    // list of unacceptable values.  The set of unacceptable values is specified via
    // the list property on the validator, which should be set to an array of
    // values. If validator.list is not supplied, the valueMap for the field will be used.
    // If there is no valueMap, not providing validator.list is an error.
    Validator.addValidatorDefinition("isNotOneOf", {
        type: "isNotOneOf",
        title:"Value not in list",
        description: "Is not one of list",
        valueType:"valueSet",
        dataType:"none",
        valueAttribute:"list",
        condition : function (item, validator, value, record) {
            // skip empty fields
            if (value == null || isc.is.emptyString(value)) return true;
    
            // get the list of items to match against, either declared on this validator
            // or automatically derived from the field's valueMap (item.valueMap)
            var valueMap = validator.list || (item ? (item.getValueMap ? item.getValueMap()
                                                                       : item.valueMap)
                                                   : null),
            valueList = valueMap;
            if (!isc.isAn.Array(valueMap) && isc.isAn.Object(valueMap)) {
                valueList = isc.getKeys(valueMap);
            }
    
            if (valueList != null) {
                // if any item == the value, return false
                for (var i = 0, length = valueList.length; i < length; i++) {
                    if (valueList[i] == value) return false;
                }
            }
            // otherwise, valid return true
            if (!validator.errorMessage) {
                validator.defaultErrorMessage = isc.Validator.notOneOf;
            }
            return true;
        }
    });
    Last edited by jaredm; 7 Dec 2015, 10:48.

    #2
    Thanks for posting this! We're not sure yet whether we'll incorporate it or what version it will land in, but even as is, it's useful code for others.

    Comment

    Working...
    X