Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Custom validate function #337

Open
mete89 opened this issue Jun 18, 2020 · 1 comment
Open

Custom validate function #337

mete89 opened this issue Jun 18, 2020 · 1 comment

Comments

@mete89
Copy link

mete89 commented Jun 18, 2020

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

@aguscha333
Copy link

aguscha333 commented Sep 5, 2020

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants