gtournie / redux-form-validators Goto Github PK
View Code? Open in Web Editor NEWredux-form-validators
redux-form-validators
Hello,
How do you handle optional file input ? Because I've multiple inputs with some optionals and by default, when user didn't touch optional input, it will throw an error "is not a file", but it should do it only when required, no ?
// Optional - Shouldn't throw "is not a file" error
<Field
name="foo"
component={InputFile}
validate={[file()]}
/>
// Required - Should throw "is not a file" error
<Field
name="bar"
component={InputFile}
validate={[required(), file()]}
/>
"//website.com" is not being recognized as invalid url. Seems like the "?" directly before two slashes ("(https?)?//") in url.REG_URL shouldn't be there. Or am I missing something and strings starting with "//" are correct? Example here: https://regex101.com/r/vQ4BNR/1/
Hey,
I am struggling to find a comprehensive list of changes between releases, could anyone point me to it please?
Thanks!
Hi. I got a problem. I working with typescript and storing empty initial value with number
type as NaN
.
For my field i using toString
formatter and toNumber
parser.
So, my value lifecycle looks like:
Store -> formatted input -> parsed value
Variant 1) NaN -> '' -> NaN
Variant 2) 1 -> '1' -> 1
I noticed, that prepare
helper converts NaN
to 'NaN'
string, and after that required
validator can't properly validate NaN
value.
Will happy if you fix it.
Thanks for implement this validatiors, it is great :)
I have a question...during I read this documents, I just found that it supports sync validation. Does it support aync validaiton? Are there any examples?
Right now it says "not a number", which users will think is a bug since 1.5 is clearly a number.
Hi! This looks very sweet as I was copying and pasting a lot of these functions between projects. Just a question is it possible to change the default error messages?
And another question, is there a reason you named all functions without a prefix? In my projects I often have email
or url
already assigned and my validators are with a small prefix which makes it a bit clearer to myself like isEmail
and isUrl
.
In playing with the demo, I noticed that inputting 5/30/55 gave me the error that I must be at least 20 years old.
Obviously, there are relatively easy ways around this for the programmer-user (including using a 4-character year or a date picker). I was surprised to see such an obvious problem in the demo (for anyone over the age of around 49-1/2 ;-).
Nevertheless, thanks for a great product!
Similar to allowBlank
I would like to allow white space around the user's input.
Upon onBlur
it will be normalised and trimmed.
I use this Field
replacement for on-blur-normalization:
https://github.com/jcoreio/redux-form-normalize-on-blur
Use cases are:
I'm trying to use addValidator
in a TypeScript project, and have :
import addValidator, { Validator } from 'redux-form-validators'
export const validPassword = addValidator({
defaultMessage: 'must contain at least one number, one lower case and one upper case letter',
validator: (options: Validator) => {
return (/[a-z]/.test(options.value) && /[A-Z]/.test(options.value) && /[0-9]/.test(options.value))
}
})
when trying to import this, I'm getting:
compilation_1 | Failed to compile.
compilation_1 |
compilation_1 | /srv/server/client/src/components/form/validators.ts
compilation_1 | (3,30): Cannot invoke an expression whose type lacks a call signature. Type '{ formatMessage: (msg: MessageDescriptor) => string; formatSize: (size: string, units: string) =>...' has no compatible call signatures.
I can see index.d.ts was added as part of #29, do we need a type to use addValidator
?
When I add validate numericality
. And This field always catch validate numericality
however this field does't have value. How can I pass this validate without value in field?
Currently, the prepare
helper method converts all values to string. So, if the <Field />
pass an object as value, the validator function will receive something like "[object Object]"
.
This makes harder to validate any type of object, specially File
objects from <input type='file' />
.
Redux form throws a warning when you don't give a form section a name. But if you do give it a name this line of code doesn't work because allValues consists of an object with a property name of the form section:
var fieldValue = typeof allValues.getIn === 'function' ? allValues.getIn(field.split('.')) : allValues[field];
I think there should be an option if it's a formsection: allValues[formSection][field]
Or am I doing something wrong?
Hi!
Will it works with redux-form immutablejs?
When I try to build my production build I got:
Versions tested: 2.4.1, 2.3.2
2.2.0 works.
> react-scripts build
Creating an optimized production build...
Failed to compile.
Failed to minify the code from this file:
./node_modules/redux-form-validators/src/helpers.js:20
Read more here: http://bit.ly/2tRViJ9
The RegEx for the email validation does not accept empty string. I think the RegEx should accept also empty string because there is a separate required validator.
The RegEx could look like this: /(^$|^[a-z0-9!#$%&'+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_
{|}~-]+)@(?:a-z0-9?.)+a-z0-9?$)/
Not sure if this is an issue with my build environment
(typescript transpiled to ES2015), but getting an Expected identifier error in IE11 when it declares the various validators:
let absence = Object(__WEBPACK_IMPORTED_MODULE_1__helpers__["e" /* memoize */])(function ({ message, msg, 'if': ifCond, unless }={}) {
msg = msg || message
return Object(__WEBPACK_IMPORTED_MODULE_1__helpers__["f" /* prepare */])(ifCond, unless, false, function (value) {
if ('string' === typeof value ? value.trim() : Object(__WEBPACK_IMPORTED_MODULE_2__file__["c" /* isFileList */])(value) && !isNaN(value.length) ? value.length : value) {
return __WEBPACK_IMPORTED_MODULE_0__index__["default"].formatMessage(Object(__WEBPACK_IMPORTED_MODULE_1__helpers__["g" /* prepareMsg */])(msg, 'absence'))
}
})
})
etc.
I'm using this validators in one my project and in a case for registration form I'm looking for a validation to check if user's entered email is unique or not using a back-end API.
Can we have a validator of this type as well ?
Thanks
This example:
import { required, email } from 'redux-form-validators'
<Field name="email" type="email" label="Email" component={renderField}
validate={[required(), email()]} />
If you're using the 6.6.x version of redux-form
return this warning message:
Failed prop type: Invalid prop `validate` of type `array` supplied to `Field`, expected `function`
The issue is fixed if we update redux-form
to the 7.x.x
version
I think that would good idea add to the documentation this comment.
cc @gtournie
Hi!
I begin use a redux-form-validators, but have issue: I make:
<Field ....... validate={url({allowBlank: true})}
I think, that if my Field is empty, error will not show. But I see error on empty (blank) field after load form.
I review a source of url.js, but not see a allowBlank processing. :(
How best way use url validator for field level validation?
Hello,
I am using Final Form. I have an e-mail field that is optional.
How would you validate only if the user tried to enter a wrong e-mail? I have succeeded to do this but I didn`t like the solution:
import * as vld from 'redux-form-validators';
<Field name="email" label="E-mail de Contato" placeholder="Deixe seu e-mail" component={TextInputField} validate={emailIfNotEmpty} />
The custom validator code is like this:
const emailIfNotEmpty = (value, allValues, meta) => { if (meta.dirty) { return vld.email()(value); } }
Can you suggest a better approach?
Kind Regards,
Mário
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/absence.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/absence.js -> node_modules/redux-form-validators/lib/helpers.js -> node_modules/redux-form-validators/lib/format.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/helpers.js -> node_modules/redux-form-validators/lib/format.js -> node_modules/redux-form-validators/lib/helpers.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/absence.js -> node_modules/redux-form-validators/lib/helpers.js -> node_modules/redux-form-validators/lib/format.js -> commonjs-proxy:/Users/lucamele/git/aletheia/node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/helpers.js -> node_modules/redux-form-validators/lib/format.js -> commonjs-proxy:/Users/lucamele/git/aletheia/node_modules/redux-form-validators/lib/helpers.js -> node_modules/redux-form-validators/lib/helpers.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/absence.js -> node_modules/redux-form-validators/lib/helpers.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/absence.js -> node_modules/redux-form-validators/lib/file.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/acceptance.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/add-validator.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/confirmation.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/date.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/inclusion.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/length.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/numericality.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/presence.js -> node_modules/redux-form-validators/lib/index.js
(!) Circular dependency: node_modules/redux-form-validators/lib/index.js -> node_modules/redux-form-validators/lib/url.js -> node_modules/redux-form-validators/lib/index.js
Validation 'confirmation' works fine in field-validation-form but fails if applied in general-validation-form - validation fails with 'doesn't match Password
'
Hi,
I faced with problem when I used you lib.
E.g. I have to do validate redux form infront of some props values:
const { form, quantity, totalBought, t } = props;
validateForm({
[`fieldId${form}`]: numericality({
greaterThan: quantity - totalBought,
message: t('error'),
}),
});
in regular redux form validation I get props from validate function:
reduxForm({
validate: (values, props) => {...})})
In your lib examples, as I can see, the validate object cannot be feed with component props or I missed something?
Thanks
When using the email()
validator the following error will appear in the console:
[React Intl] Cannot format message: "form.errors.email", using message id as fallback.
I guess it has something to do with this (unused) variable:
redux-form-validators/src/email.js
Line 8 in 652c095
Related to https://github.com/gtournie/redux-form-validators/blob/master/examples/src/index.js#L25.
I'm working with Redux-Saga and it watches for "CHANGE_LOCALE"
action:
// saga
export function* changeLocaleSaga(action: routines.setLocaleAction) {
yield call(LocaleService.configureReduxFormValiators, action.payload);
}
yield all([
takeEvery(routines.CHANGE_LOCALE, changeLocaleSaga),
]);
And in Locale Service I mutate the Validators:
// Locale.service
function configureReduxFormValiators(locale: ISupportedLocale) {
const messages = getTranslationsByLocale(locale);
Validators.messages = {
...Validators.messages,
email: messages['component.field.error.isNotValidEmail'],
};
}
export const LocaleService = {
// getTranslationsByLocale,
// getSupportedLocaleByLocale,
configureReduxFormValiators,
};
BUT the problem here that Validators mutation doesn't tell React to re-render.
Please advice.
So basically file validation runs with empty files list producing "is not a file" error.
Any piece of advice would be highly appreciated.
<Field
component={FieldUploadFile}
type="file"
name="attachments"
label={<FormattedMessage id={messageIds['entity.ticket.field.attachments']} />}
validate={[file({ allowBlank: true, maxFiles: 10, maxSize: '1 MB' })]}
/>
export function FieldUploadFileBase(props: IProps) {
const [attachments, setAttachments] = React.useState<File[]>([]);
const handleFileDrop = React.useCallback(
(item: any, monitor: DropTargetMonitor) => {
if (monitor) {
const files = monitor.getItem().files;
setAttachments(attachments.concat(files));
}
},
[attachments],
);
const handleFileSelect = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files) {
const selectedFiles = Array.from(e.target.files);
setAttachments(attachments.concat(selectedFiles));
}
}, [attachments]);
const onRemoveFile: AttachmentProps['onRemoveFile'] = (fileToRemove) => {
setAttachments(attachments.filter((attachment) => attachment !== fileToRemove));
};
React.useEffect(() => {
props.input.onChange(attachments);
}, [attachments]);
return (
<FormControl fullWidth>
<Box marginBottom={3}>
<AttachmentTargetBox onDrop={handleFileDrop} handleFileSelect={handleFileSelect} />
</Box>
<AttachmentsList files={attachments} onRemoveFile={onRemoveFile} />
<p>{props.meta.error}</p>
</FormControl>
);
}
So someone thought they could be clever and avert the need to declare constant validator
functions outside of React Elements by memoizing the validator creators.
In general, caching functions passed into your library is bound to cause problems, because of closures.
Here's how it screwed me over:
export default class PrefixTagsWithFields extends React.Component<PrefixTagsWithFieldsProps> {
validateCustomPrefix = required({
// should work, right?
if: values => get(values, `${this.props.sectionPrefix}.prefixTagsWith`) === CUSTOM_PREFIX,
})
render(): React.Node {
const {classes} = this.props
return (
<CustomPrefixField
className={classes.field}
validate={this.validateCustomPrefix}
/>
)
}
I was rendering a <PrefixTagsWithFields sectionPrefix="one" />
and a <PrefixTagsWithFields sectionPrefix="two" />
, but when my if
logic above runs, this.props.sectionPrefix
is always one
, which was a real head scratcher.
Finally I dug in the memoize
function inside redux-form-validators
. Here is the cache key for my required
validator above. The cache key is unable to differentiate between the different instances of my component:
"["if","function _if(values) {\n return lodash_get__WEBPACK_IMPORTED_MODULE_0___default()(values, _this.props.sectionPrefix + '.prefixTagsWith') === _types_MQTTDevice__WEBPACK_IMPORTED_MODULE_12__[\"CUSTOM_PREFIX\"];\n }"]"
So when <PrefixTagsWithFields sectionPrefix="two" />
tries to create its validator it gets back one with the wrong closure.
Any plans for supporting redux 4.0.0? It doesn't look like it's supported now, as per package.json
Using arrays to combine validators may introduce unnecessary updates (as a new array is created on each render).
<Field
validate={[required(), email()]}
/>
If redux-form-validators
provided an every
combinator, which would memoize similarly to other validators, this could be avoided.
<Field
validate={every(required(), email())}
/>
While we at it, why not add some
with the opposite meaning of "at least one validator should pass".
I'd like to use this library as I love the idea of having these commonly used validation scenarios but don't want to add the complexity involved with react-intl.
I was wondering if it is possible to create custom properties such as the following example:
validate={[isRequired({ intl: false }), isEmail({ intl: false })]}
which would be preferably be able to use in the formatMessage
function eg:
Validators.formatMessage = (msg, props) => {
if (props.intl) {
// Stuff
}
else {
// Stuff
}
}
title says it all
Hi
I'm not sure how to use validation messsages with length. When I make something like this:
<Field
id="title"
type="text"
name="title"
placeholder="Ener title"
component={Input}
label="Title"
helpText="Min 5, max 70"
validate={[required({message: 'Required'}), length({
min: 5,
max: 70,
messages: {
tooShort:"Title is too short",
tooLong:"Title is too long"
}
})]}
/>
I can see only default message. I've tried with msg, massage but it doesn't work.
How can I apply tooShort and tooLong messages ?
example fails on Linux: import of App in examples/src/index.js should be changed:
-import App from './app';
+import App from './App';
At the moment if
and unless
take in values
and value
. Redux-form also provides props
and name
to the validator. Can these additional arguments (or at least props
) also be passed through to the if
and unless
functions?
This would get around some of the issues with memoization (#44 (comment)) without being a breaking change.
I'm using the suggested way to implement default messages as you mentioned #17 and is working great but I currently receive an error when the following custom validator
does not trigger
import { addValidator } from "redux-form-validators";
export default addValidator({
validator: (options, value, allValues) => {
if (!/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/i.test(value)) {
return {
id: "hexCode",
values: { hexCode: value }
};
}
}
});
When I load the page with the validator
it triggers the following error Cannot read property 'id' of undefined
which refers to the function below. This only fires when the validator
is passing eg returns nothing
export default function createDefaultReduxErrorMessages(customErrorMessages, FormattedMessage) {
return (Validators.formatMessage = (msg) => {
const errorMessages = { ...defaultMessages, ...customErrorMessages };
if (msg.id) {
const type = msg.id.replace("form.errors.", "");
msg.defaultMessage = _.get(errorMessages, type, undefined) || msg.defaultMessage;
if (FormattedMessage) {
return <FormattedMessage {...msg.props || { ...msg, id: `form.${type}` }} />;
}
}
return originalFormatMessage(msg);
});
}
Am I doing something wrong in my custom validator
or should I just put the return
statement of the createDefaultReduxErrorMessages
in the if (msg.id) {...}
?
I am trying to create a reusable isBirthday
validator for my different projects. When trying this I've created a createDefaultReduxErrorMessages
(that naming 🔥 ) to make sure I don't repeat myself setting up default error messages and settings. This is working great for me however when trying to add a custom validator I also want that validator to use the Validators.formatMessage
(see example at the bottom).
The problem lies in that when I return an object with id
, defaultMessage
and values
from my custom validator it thinks it needs to render the object to the component as the error while totally ignoring my Validators.formatMessage
function.
How do I make custom validators use the Validators.formatMessage
function is well?
createDefaultReduxErrorMessages
import React from "react";
import Validators from "redux-form-validators";
const originalFormatMessage = Validators.formatMessage;
const defaultMessages = {
presence: "Required",
email: "Invalid e-mail adress",
// Stuff
};
export default function createDefaultReduxErrorMessages(customErrorMessages, FormattedMessage) {
return (Validators.formatMessage = (msg) => {
const errorMessages = { ...defaultMessages, customErrorMessages };
if (msg.id) {
const type = msg.id.split(".").pop();
msg.defaultMessage = errorMessages[type] || msg.defaultMessage;
if (FormattedMessage) {
return <FormattedMessage {...msg.props || { ...msg, id: `form.${type}` }} />;
}
}
return originalFormatMessage(msg);
});
}
Example of custom validator
import { addValidator } from "redux-form-validators";
export default addValidator({
validator: (options, value, allValues) => {
const onlyNums = value.replace(/[^\d]/g, "");
const day = onlyNums.slice(0, 2);
const month = onlyNums.slice(2, 4);
const year = onlyNums.slice(4, 8);
const currentYear = new Date().getFullYear();
if (day > 31 || day === "00") {
return {
id: "birthday.day",
defaultMessage: "Invalid day",
values: {}
};
}
else if (month > 12 || month === "00") {
return {
id: "birthday.month",
defaultMessage: "Invalid month",
values: {}
};
}
else if (year > currentYear || year < currentYear - 120) {
return {
id: "birthday.year",
defaultMessage: "Invalid year",
values: {}
};
}
}
});
I'm trying to use redux-form-validators with react-final-form library however it's still complaining of missing dependency error for redux-form.
Can this be fixed please?
When I import any of the validators from redux-form-validators into my component, I get the following error
Uncaught SyntaxError: Unexpected token import
Which points somewhere here
/*!**********************************************!*\
!*** ./~/redux-form-validators/src/index.js ***!
\**********************************************/
/***/ function(module, exports) {
import absence from './absence'
import acceptance from './acceptance'
import addValidator from './add-validator'
import confirmation from './confirmation'
Anyone else facing this issue? I am using CRA, redux form validators version 2.0.0
There doesn't seem to be a way to use sync validation or field validation with field arrays. Is this not supported or am I missing something?
When evaluating (with Redux Form's "validate" function approach), the returned object is always a FormattedMessage.
Expected result: If 'message' is not explicitly a FormattedMessage, then a regular string should be returned with the message.
Failed to minify the code from this file: ./node_modules/redux-form-validators/src/index.js:19
Can you please publish a precompiled version of the lib to npm?
I'm a bit of a react noob, so I apologize if this is obvious. I'm working on a project with lots of redux-forms. So far so good. I wrote some of my own validators in the redux-forms prescribed way. These are better. I'd like to use them, and I can use them, but I'd basically like to be able to override the default messages in one place, add a few validators, and then import and reference them from any given component that contains a redux-form. Is there an easy way to do this?
Hi,
I have explained the code and situation in detail in this thread
I believe this is an issue related to the redux-form-validators. Can anyone help me check this?
Thanks
I did a function that support nested validation.
import { required, email, length } from 'redux-form-validators';
const validations = {
myInfo:
{
address: [required(), length({ max: 20 })],
email: [required(), email()],
},
laboratory: {
address: [required(), length({ max: 15 })],
email: [required(), email()],
},
};
// Reusable with any other form
const validateNested = (values, validations) => {
const errors = {};
Object.keys(validations).forEach(field => {
let value = null;
if (values) {
value = values[field];
}
if (validations[field].constructor === Array) {
errors[field] = validations[field].map(validateField => {
return validateField(value);
}).find(firstErrorMsg => firstErrorMsg);
} else {
errors[field] = validateNested(value, validations[field]);
}
});
return errors;
};
const validate = values => {
return validateNested(values, validations);
};
export default validate;
fileTooBig: {
id: "form.errors.fileTooBig",
defaultMessage: "{count, plural, one {is} other {{count} files are}} too small (maximum is {count, plural, one {{size}} other {{size} each}})"
},
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.