ansman/validate.js

Custom validate function

Opened this issue · 1 comments

Hey @ansman ,

I have a simple question. Can I invalidate something inside custom function with a message?

function(value, attributes, attributeName, options, constraints) {
    if(attributes["key"] !== "b") {
        return 'Value b is not allowed';
    } else {
        return null;
    }
};

Or do I need to escalate it to validators such as presence, inclusion etc?

Thanks

You can write your own validators for sure! It should also look very similar to what you have now but with some tweaks.

You need to actually add your validator to validate and the params it can receive are a bit different:

validate.validators.myCustomValidator = (
  value,
  options,
  key,
  attributes,
) => {
  // validate here. Return the error as a string and it should count it as an error no problem.
  //In your case:
  if(attributes["key"] !== "b") {
    return 'Value b is not allowed';
  } else {
    return null;
  }
};

Options is what you specify in the constraint when using it:

const myConstraints = {
  someField: {
    myCustomValidator: {
      // these are the options you will receive
    }
  }

All of this is actually documented already in the library docs. I encourage you to take a look.
Here is the link to the specific part you want in the docs: https://validatejs.org/#custom-validator

By the way, I don't quite understand what you are trying to validate. You are trying to return as an error that the value of another attribute is not allowed? why is that validation not being done in that field?

Hope this information helps.