newoldmax / react-form-validator-core Goto Github PK
View Code? Open in Web Editor NEWCore validator component for react forms
License: MIT License
Core validator component for react forms
License: MIT License
Hi guys, first thank you for your work. Your package is the only one that covered all my uses cases... Until now.
I'm trying to make a Radio ValidatorComponent (RadioGroupValidator) that contain some Radio components (<input type="radio" {...props} />
). I use the "required" rule with an error message as it is a radio (I just want to check if at least on radio has been checked).
The problem is that when i submit my form, the error appears event if one of my radio is checked.
I make the error disappear with the "makeValid" methode of ValidatorComponent but when validation is call it still returns an error.
Is it possible to handle multiple inputs component with react-form-validator-core?
(radio, checkbox...)
If yes can you give an example ?
I am using react-material-ui-form-validator (which depends on react-form-validator-core) in one of my projects and every form throws a warning when submitting like this:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method preventDefault
on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See https://fb.me/react-event-pooling for more information.
This happens in ValidatorForm.jsx in the submit method.
react - v16.8.4
react-material-ui-form-validator - v2.0.7
react-form-validator-core - v0.6.2
This package is not published pre-compiled. So create-react-app can not build this package with this error:
Failed to minify the code from this file
Please refer to this link:
https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-build-fails-to-minify
Thank you
Hi, I would like to add two new validation rules
matchRegexp: (value, regexp) => {
const validationRegexp = (regexp instanceof RegExp ? regexp : (new RegExp(regexp)));
return (!isExisty(value) || isEmpty(value) || validationRegexp.test(value));
},
I don't see how one can pass a regex? For example I am wanting to use modifiers such as the case insensitive 'i' but ['matchRegep:/^[a-z0-9]+$/i']
gets handled as a string and doesn't work. I saw an issue on formsy react with a similar unanswered question so perhaps it stems from that.
I am able to do what I need using [A-Za-z0-9]
for my needs so this is more of a general curiosity question.
I cannot find the @types/eact-form-validator-core and I cannot use react-form-validator-core yet in a typescript project. Linting is failing on every component extending ValidatorComponent.
Any suggestion?
Hi,
After adding a custom validation rule with ValidatorForm.addValidationRule
in componentDidMount()
, I think it is reasonable to remove it in componentWillUnmount()
. It looks like there could be a memory leak because the custom rule function stays in the Rules collection with all its closures.
Why there is no ValidatorForm.removeValidationRule
?
Thanks.
I am having a form for signing, having as state
this.state = {
email: '',
fullName: '',
}
I am using the ValidatorForm
alongside the ValidatorComponent
. And it is working successfully.
But I would like to clean my fields values on success submit, the idea was naturally to clean state value as follow:
handleSubmit = () => {
...call the backend
setState({
email: '',
fullName: '',
})
};
This is retriggering the validation process, causing the required field message
to reappear.
I have got the idea of using ValidationForm.resetValidations();
to reset all validation
And now my handleSubmit()
methods looks like this:
import { ValidatorForm } from 'react-form-validator-core';
...
handleSubmit = () => {
...call the backend
ValidationForm.resetValidations();
setState({
email: '',
fullName: '',
})
};
But I am getting this error:
Possible Unhandled Promise Rejection: TypeError: react_form_validator_core__WEBPACK_IMPORTED_MODULE_3__.ValidatorForm.resetValidations is not a function
at Object.Contact.handleSubmit [as onSubmit] (Contact.jsx:93)
at ValidatorForm.js:83
at index.js:53
at run (setImmediate.js:40)
at runIfPresent (setImmediate.js:69)
at onGlobalMessage (setImmediate.js:109)
Hi. I've special validation case. Literally we should not allow to submit form if component marked as Claimed, while the value was not changed.
Next code, works fine, it's check if this field is claimed, marks it's as invalid and trigger related error msg. But it's works only visually, user can submit this form despite that was not changed=invalid.
I tried all possible ways to achieve this result and didn't get success. makeInvalid etc seems that not working, because this.validate() overwrite isValid state on form submit.
Is it possible somehow extend/override validate() method to prevent from submit when it's not valid based on custom rule?
return class ClaimedValidator extends ValidatorComponent {
constructor(props) {
super(props)
this.state = { ...this.state, changed: false, initialValue: ''}
}
onChangeValue(value) {
const {onChange} = this.props;
onChange(value);
if (!this.state.changed) {
this.setState({initialValue: this.props.value})
}
this.setState({changed: true})
}
getHelperText() {
const {isValid} = this.state;
const {claimText, helperText} = this.props;
if (isClaimError(this.props, this.state)) {
return claimText;
}
else if (!isValid) {
return this.getErrorMessage() || helperText;
}
}
render() {
/* eslint-disable no-unused-vars */
const {
onChange,
errorMessages,
validators,
requiredError,
helperText,
validatorListener,
withRequiredValidator,
claimText,
claims,
...rest
} = this.props;
const { isValid } = this.state;
return (
<WrappedComponent
{...rest}
error={!isValid || isClaimError(this.props, this.state)}
helperText={this.getHelperText()}
onChange={this.onChangeValue.bind(this)}
/>
);
}
}
I have a return of the api, with an error for my form element.
And I made a validation function.
But, how can I trigger this after api returns my error?
ValidatorForm.addValidationRule('hasApiEmailError', (value) => {
if (form_error && form_error.email && form_error.email.errors) {
return false;
}
return true;
});
<TextValidator
fullWidth
label="Email"
name="email"
type="email"
value={ user.email }
validators={ ['required', 'isEmail', 'hasApiEmailError'] }
errorMessages={ ['this field is required', 'email is not valid', this.getErrorMessage(form_error, 'email')] }
onChange={ (event) => this.handleChange(event) }
/>
I am using react-form-validator-core in one of my projects, and I have noticed that I am getting a warning while performing certain actions. I have stripped down the code to the minimum where I can consistently reproduce this issue. You can find the code at https://github.com/ahdeshmukh/react-form-validator-core-warning.git
This is observed in Chrome and Edge. Did not test on any other browsers.
This warning appears only on page load. You can see the textbox again by clicking on the Clear State button. No warning is thrown if you submit the form again without refreshing the page.
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
validate()
is never called with includeRequired
, and
required
ValidateOnChangeAfterInitialBlur
Hey Guys, i want to add a new validation rule to check if mail is available.
Somethink like
ValidatorForm.addValidationRule('isEmailAvailable', (value) => {
axios.post('/api/users/emailavailable', formDataClear)
.then((response) => {
if (response.data == "ok") {
return true
}
return false
})
});
Is there a way to set async validators?
Hi,
Can you add a property or method to the ValidatorForm to see if the whole form is valid or not.
Something like
isValid=()=> { this.childs.map(child => { if(child.isValid) { return true } }); return false }
I have the following code
handleFullnameChange = (fullname) => {
console.log(fullname);
this.setState({ fullname });
this.refs['form'].isFormValid(false).then((response) => {
console.log("is Valid "+response)
});
}
And this too
<Form
ref="form"
onSubmit={this.handleSubmit}
>
<TextValidator
name="fullname"
placeholder="Full Name"
validators={['minStringLength:3']}
value={fullname}
onChangeText={this.handleFullnameChange} />
I'm expecting that when I type 3 characters that the log will return "is Valid true". Instead it returns "is Valid false" on the first 3 times I type a letter, and then returns "is Valid true" on the 4th time.
Hi,
It seems that the latest release (to support React 16) is missing the last 3 rules (isString, minStringLength & maxStringLength).
Could you make another release with all the features (added by @skorp) ?
Thanks :)
Hi,
In mostly "add new screen", object's properties will be null.
Without input anything, the text field have null value should still satisfy all maxStringLength validation.
Current code : https://github.com/NewOldMax/react-form-validator-core/blob/master/src/ValidationRules.jsx#L55
Can we update it to something like this :
maxStringLength: (value, length) => !isExisty (value) || (validations.isString(value) && value.length <= length),
Thank you and Best regards,
/K
Feature Request.
I would be happy to contribute with a pull request if they are welcome?
If i send username api and response Login already exists how can set error username field ?
Using should prevent instant validation. It looks like in the ValidatorComponent.jsx you guys are checking if the this.instantValidate exists rather than calling it.
Current Code:
componentDidUpdate(prevProps, prevState) { if (**this.instantValidate** && this.props.value !== prevState.value) { this.validateDebounced(this.props.value, this.props.withRequiredValidator); } }
Suggested Fix:
componentDidUpdate(prevProps, prevState) { if (**this.instantValidate()** && this.props.value !== prevState.value) { this.validateDebounced(this.props.value, this.props.withRequiredValidator); } }
Hi
I'm trying to use this lib with react-input-mask like the example:
But if I bu like the example, nothing happens.
Have any idea to make this work?
I tried to use resetValidations, however I got error: this.form.resetValidations is not a function. And when I looked into the source in browser, I didn't even see the function under ValidatorForm.js.
I think the reason is we didn't bind it correctly in ValidatorForm.
For example, if you have a New Password and a Confirm New Password field, you can't make the Confirm New Password field validation switch to true if the New Password field changes.
@NewOldMax It is not able to detect if form is dirty or touched and feature to make it dirty by function
Upon adding custom validations, on no error the validator is getting called infinite times. I think this is the same issue christianalfoni/formsy-react#298.
"react": "^16.4.2",
"react-form-validator-core": "^0.4.4",
Hi @NewOldMax ,
Thanks for providing the isFormValid() method to get the form state if its valid or not.
I was trying to use it in the validatorListener but it keeps going into infinite loop. Where do you suggest we should use isFormValid() method?
@NewOldMax please check this link . I want both input field dependent to each other.
Originally posted by @DeepakM02 in #50 (comment)
I am implementing form validation inside my material-ui TextField as follow:
class TextInput extends ValidatorComponent {
/**
* render the component
* @returns {object} JSX
*/
render() {
const {
variant,
id,
label,
autoFocus,
multiline,
rows,
error,
errorMessages,
validators,
requiredError,
helperText,
withRequiredValidator,
...rest
} = this.props;
const { isValid } = this.state;
return (
<TextField
{...rest}
fullWidth
margin="normal"
variant={variant}
id={id}
name={id}
label={label}
autoFocus={autoFocus}
multiline={multiline}
rows={rows}
error={!isValid || error}
helperText={(!isValid && this.getErrorMessage()) || helperText}
/>
);
}
}
TextInput.propTypes = {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
error: PropTypes.bool,
helperText: PropTypes.string,
variant: PropTypes.string,
autoFocus: PropTypes.bool,
multiline: PropTypes.bool,
rows: PropTypes.string,
};
TextInput.defaultProps = {
error: false,
helperText: undefined,
variant: 'outlined',
autoFocus: false,
multiline: false,
rows: '8',
};
export default TextInput;
<ValidatorForm
className={classes.form}
autoComplete="off"
noValidate
onSubmit={this.handleSubmit}
>
<TextInput
id="email"
label="Email"
autoFocus={false}
onChange={this.onChange}
value={email}
validators={['required', 'isEmail']}
errorMessages={['this field is required', 'email is not valid']}
/>
<Box marginTop={2}>
<Button variant="contained" type="submit" className="button" fullWidth>
send message
</Button>
</Box>
</ValidatorForm>
I don't understand why every time I enter a value on the TextField, I am getting this error:
Uncaught TypeError: _this.props.validatorListener is not a function
Would like to know the effective way of using this library alongside material-ui
Hello,
I've using [email protected]
on my project scaffolded by create-react-app
and on build to production step react-scripts build
throws the error:
Failed to minify the code from this file:
./node_modules/react-lifecycles-compat/react-lifecycles-compat.es.js:64
The real problem is related here, and the solution is the react-form-validator-core
upgrade the dependency version of react-lifecycles-compat
to 3.0.2+
if you are using version 0.4.3
.
On version 0.4.4
all works as expected.
I have added these props to my file input:
validators={['isFile', 'maxFileSize:' + 2 * 1024 * 1024, 'allowedExtensions:image/png,image/jpeg']}
errorMessages={['File not valid.', 'The file size must not exceed 2MB.', 'The file must be png or jpeg.']}
But when I don't add a file, it still shows "File not valid" (or the first error of the array)
Hey there, since ""
is not a valid email, one would expect that isEmail("")
return false
instead of true
.
Hi, I am playing a bit with the validators and so far it looks great.
I just came across this little issue:
I used a <TextValidator>
component (from react-material-ui-form-validator) with type="email"
and I got the browser's validator kicking.
Solution was to add noValidate
to <ValidatorForm>
but since this library is all about doing custom validation, I guess it should probably come by default here?
What do you think?
isFormValid | dryRun: bool (default true) | bool | Get form validation state (true if whole form is valid). Run with dryRun = false to show validation errors on form |
---|
but i am getting return value as promise. I try to check the code and found the same
https://github.com/NewOldMax/react-form-validator-core/blob/master/src/ValidatorForm.jsx#L149
-> https://github.com/NewOldMax/react-form-validator-core/blob/master/src/ValidatorForm.jsx#L69
Let me know if I am missing something.
Is there planned support for radio type (or perhaps something I'm missing in what's currently available)?
In the source, it looks like your forcibly looking at value
, value = _input$props.value,
in ValidateForm.js
.
Is there a plan to allow a prop to specify a key (naturally defaulted to "value") such as 'checked'.
However, it looks like you probablyhave to either:
I have used InputMask component in side of TextValidator and its worked fine in react.15x after updating its not working. Please check below code. How i can make it happen please help us
<TextValidator
validatorListener={this.validatorListener}
hintText="Home Phone"
value={this.state._phone1}
className="drawer-form-input-text"
label="Home Phone"
name="bill_phone1"
key="bill_phone1"
onChange={this.handleSecondryContact}
>
<InputMask
hintText="Home Phone"
value={this.state.secondryContact.bill_phone1}
mask="(999) 999-9999"
onChange={this.handleSecondryContact}
className="drawer-form-input-text"
name="bill_phone1"
/>
</TextValidator>
validation not working on checkbox group.
Hello, I'm having an issue with a form that has multiple TextValidators with the same name
prop value. I'll try to explain a simplified version of my setup for some context.
I have a component that contains an array of objects of type A. So, for example, each of these A objects has a name, description, etc because they're all of the same type. I'm rendering a form that contains TextValidator components for the fields that are editable on these A objects. So, after rendering an entire form containing form fields for this array of object, there will be multiple TextValidators with the same name
prop because I'm using a sub-component to render these objects. In order to update the state of this array of objects, the sub-components just pass an index to a onUpdate
handler with the onChange event which is just the browser event. So, using the index and the browser event (and more specifically event.target.name), the parent component knows how to update the correct A object that it is managing because it can index into its array of A objects and then use event.target.name to update the correct field value.
It seems, however, that the ValidatorForm component requires that TextValidator names be unique because of this line where it tries to find a child component of the form that has the same name as the input. If you have more than 1 input with the same name, then that find()
call will only ever return the first one (as far as i can tell).
So, I have two questions about that. The first is: should name
props of TextValidators be unique? The second is: In my debugging and in that particular piece of code I referenced, input
is always a TextValidator component, so why would you then need to find a child component with the same name if you've already got the component? If that code just used the input
param passed to the validate
function, then I think my issue would be solved because the submit()->walk()->checkInput()
function chain wouldn't care about matching names, it would just go through each form field and validate them regardless of names.
This is a problem mainly on submit because the default onSubmit handler in ValidatorForm rolls through all of its managed inputs and checks to see which ones are invalid by name (and has runs into the issue I mentioned above). So, currently the form I have will only display the first field with a given name as being invalid and any others will just remain in a normal state (no error message, no red outline, etc.)
Sorry for being a bit long-winded. Any advise?
I'm trying to set the "instantValidate" property dynamically and there is no effect.
I've also tried to use refs like you suggested here (#33 (comment)), and I can successfully alter the property via the ref, but it as no real effect.
I have next warning when I am using debounceTime,
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method
my code:
<ValidatorForm
onSubmit={this.handleSubmit}
debounceTime={1000}
ref={this.form}
>
When I am typing something in validation input and then I change route or close form component I always get this Warning, without debounceTime everything works correctly, but I need debounceTime.
As I understand we need unsubscribe from debounceTime before component will unmaunt, but how can I handle it?
Please help me if you can
Hi. Many things doesn't work.
I have code example:
<ValidatorForm instantValidate={false} onSubmit={::this.submit} className="form">
<Input
validators={['required', 'matchRegexp:^@+.?' ]}
errorMessages={['this field is required', 'telegramm link should be like in example @your_name']}
value={contactInfo && contactInfo.telegramAccount}
name="contactInfo.telegramAccount"
/>
</ValidatorForm>
and part of my Input component:
class Text extends ValidatorComponent {
static propTypes = {......}
static defaultProps = {......}
constructor(props){
super(props);
this.state = {
...Text.defaultProps,
...this.props,
...{id: uniqid(this.props.name + '-')}
}
}
errorText() {....From example...}
onChange(event){
let value = event && event.target && event.target.value || '';
this.setState({
value: value
})
}
render(){
<>
<input
ref={(r) => { this.input = r; }}
onChange={::this.onChange}
value={this.state.value}
name={this.state.name}
/>
{this.errorText()}
</>
}
}
1: when page is loaded validation start to run even if instantValidate={false}.
2: when i try to change input value -validation started again.
3: I can't change input value through method onChange, value doesn't change because of method in your component getDerivedStateFromProps
4: When i submit the form your component get old value that was when the page loaded, and validation passing, however value in field have already deferent value.
Can you clarify something?
was checking out this package but noticed if you have more than one custom validator, there is a warning logged in the console.
example: https://codesandbox.io/s/9l94nrqrnw
Possible Unhandled Promise Rejection: TypeError: _ValidationRules2.default[name] is not a function at Function.ValidatorForm.getValidator (ValidatorForm.js?5676:198) at eval (ValidatorForm.js?5676:131) at Array.map (<anonymous>) at eval (ValidatorForm.js?5676:130) at doResolve (index.js?305e:129) at new Promise (index.js?305e:33) at ValidatorForm._this.validate (ValidatorForm.js?5676:123) at eval (ValidatorForm.js?5676:112) at doResolve (index.js?305e:129) at new Promise (index.js?305e:33)
Hi,
Thanks for your great lib,
I have an issue when use your add custom rule.
I add new Rule for my checkbox
ValidatorForm.addValidationRule('isChecked', (value) => { return value; });
Then, I use this rule in my component
<GMForm onSubmit={this.handleSubmit}>
<GMInput
onChange={this.handleChange}
name="email"
value={this.state.email}
className="form-control"
validators={["required"]}
errorMessages={["This field is required"]}
/>
<GMCheckbox
onChange={(e) => {
this.handleChange({
target: {
name: e.target.name,
value: !this.state.is_valid
}
});
}}
checked={this.state.is_valid}
name="is_valid"
label="How to Valid"
value={this.state.is_valid}
validators={["isChecked"]}
errorMessages={["You Must Checked"]}
/>
<ButtonPrimary type="submit">Submit</ButtonPrimary>
</GMForm>
Input work perfect with rule required
unknown errorMessages type ["You Must Checked"]
I check your lib, and see
_this.getErrorMessage = function () {
var errorMessages = _this.state.errorMessages;
var type = typeof errorMessages === 'undefined' ? 'undefined' : _typeof(errorMessages);
if (type === 'string') {
return errorMessages;
} else if (type === 'object') {
if (_this.invalid.length > 0) {
return errorMessages[_this.invalid[0]];
}
}
// eslint-disable-next-line
console.log('unknown errorMessages type', errorMessages);
return true;
Error come from _this.invalid
is a empty array.
So, What wrong in my setting new rule, can you reply me an example.
Thanks for your reading.
There are validators for text. I want to use these validator for select, desc and other input type along with text type. I am not getting what should I do.
The isFloat validation rule is not allowing negative numbers, is this correct behaviour?
Comparing to isNumber, it appears isFloat is deliberately not allowing -
:
isNumber: value => validations.matchRegexp(value, /^-?[0-9]\d*(\d+)?$/i),
isFloat: value => validations.matchRegexp(value, /^(?:[1-9]\d*|0)?(?:\.\d+)?$/i),
Have any plans for allowing validate onBlur
as a prop/config as well? I can look into opening a PR if I get some free time. Thanks for the package, it was exactly what I was looking for.
Is there any reason why onSubmit is required? If I am going to do a custom submission by ValidatorForm methods, I will have console errors onSubmit is required
true
?My scenario is the following:
What happens
Once I clear the values, <ValidatorComponent />
's didUpdate understands prev and next props are different and starts the debounced validation cycle which results in isValid
= false.
What I wanted
A way to clear the values + reset all validations, like a start again feature.
What I have tried
I have tried to use resetValidations()
, but it runs before didUpdate
lifecycle, therefore I end up with isValid
= false anyways.
The only way I managed this to work was by placing resetValidations()
inside a timeout 😞
Things I would/wouldn't want to do:
instantValidate
After going through the issue:
#41
And trying to implement the solution in codepen, here: https://codesandbox.io/s/pedantic-davinci-sxudm
After switching the handleError
to handle the promise from isFormValid
instead of the old boolean, I'm having troubles toggling disabled in state to disable/enable the submit button.
If a form is invalid, this is fine as handleError
sets disabled in state to true. However, when the form is valid I'd assume handleError
doesn't get called, so other than creating our own isValid
function which returns true
or false
and constantly calling it perhaps using validationListener
(maybe?), is there a solid way to determine a valid form so that the button is enabled?
I'm also going to have additional login in handleSubmit
, but figuring out a solution to the above problem would be useful to start! Any info is appreciated.
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.