busypeoples / spected

Validation library
MIT License
703 stars 32 forks source link

How to compare two values? #101

Open YannisMarios opened 6 years ago

YannisMarios commented 6 years ago

Hi,

How do you validate if two fields are equal, for example fields password and confirm_password?

Can you provide an example?

busypeoples commented 6 years ago

Hi! Checkout the example from the revalidation library, which uses spected to validate inputs. https://github.com/25th-floor/revalidation/blob/master/example/validationRules.js#L11 The example shows how to check if two fields are equal. Let me know you, if this solves your problem!

arizonatribe commented 6 years ago

This works great! I didn't know about it either until I cloned the repo and started trying to play with the code and I ran across those unit tests. Is it possible that something like that could make its way into the docs too? I ended up referring a co-worker to a workaround about a month ago because I didn't realized spected has that feature.

arizonatribe commented 6 years ago

Maybe a basic suggestion description pulling code directly out of the tests:


A predicate function for any of the rules will also receive the entire input object as a second parameter, allowing you to access other values at the same time. An example of this might be for password confirmation, since both values (password and the repeated password field) need to match.

// some validation helpers
const minimumMsg = (field, len) => `Minimum ${field} length of ${len} is required.`
const capitalLetterMag = field => `${field} should contain at least one uppercase letter.`
const isEqual = compareKey => (val, allValues) => val === allValues[compareKey]
const equalMsg = (field1, field2) => `${field2} should be equal with ${field1}`

const validationRules = {
  password: [
    [isLengthGreaterThan(5), minimumMsg('Password', 6)],
    [hasCapitalLetter, capitalLetterMag('Password')],
  ],
  repeatPassword: [
    [isLengthGreaterThan(5), minimumMsg('RepeatedPassword', 6)],
    [hasCapitalLetter, capitalLetterMag('RepeatedPassword')],
    [isEqual('password'), equalMsg('Password', 'RepeatPassword')],
  ]
}

const result = spected(validationRules, {password: 'fooBar', repeatPassword: 'fooBarBaz'})

deepEqual({
  password: true,
  repeatPassword: [equalMsg('Password', 'RepeatPassword')]
}, result)
busypeoples commented 6 years ago

Yes, that's a good point. Will update the documentation. Thanks for the valuable input!