An isomorphic form-handling library for React
(Formerly a direct port of the Django framework's
npm install newforms
var forms = require'newforms'
By default, newforms will be in development mode. To use it in production mode,
set the environment variable
'production' when bundling. To
completely remove all development mode code, use a minifier that performs
dead-code elimination, such as UglifyJS.
Browser bundles expose newforms as a global
forms variable and expect to
find a global
React variable to work with.
Uncompressed, with warnings about potential mistakes.
Compressed version for production.
A quick introduction to defining and using newforms Form objects.
The starting point for defining your own forms is
Here's a simple (but incomplete!) definition of a type of Form you've probably seen dozens of times:
var SignupForm = formsFormextendusername: formsCharFieldemail: formsEmailFieldpassword: formsCharFieldwidget: formsPasswordInputconfirmPassword: formsCharFieldwidget: formsPasswordInputacceptTerms: formsBooleanFieldrequired: true
A piece of user input data is represented by a
of related Fields are held in a
Form and a form input which will
be displayed to the user is represented by a
Field has a default Widget, which can be overridden.
Forms provide helpers for rendering labels, user inputs and validation errors for their fields. To get you started quickly, newforms provides a React component which use these helpers to render a basic form structure.
At the very least, you must wrap rendered form contents in a
provide form controls such as a submit button and hook up handling of form
var Signup = ReactcreateClassreturn <form onSubmit=this_onSubmit><formsRenderForm form=SignupForm ref="signupForm"/><button>Sign Up</button></form>// ...
Rendering helpers attach event handlers to the inputs they render, so getting user input data is handled for you.
RenderForm component handles creating a form instance for you, and
setting up automatic validation of user input as it's given.
To access this form instance later, make sure the component has a
The final step in using a Form is validating when the user attempts to submit.
First, use the
ref name you defined earlier to get the form instance via the
Then call the form's
validate() method to ensure every field in the form is
validated against its current user input.
If a Form is valid, it will have a
cleanedData object containing validated
propTypes:onSignup: ReactPropTypesfuncisRequiredepreventDefaultvar form = thisrefssignupFormgetFormvar isValid = formvalidateif isValidthispropsonSignupformcleanedData
There's an obvious validation not being handled by our form: what if the passwords don't match?
This is a cross-field validation. To implement custom, cross-field validation
clean() method to the Form definition:
if thiscleanedDatapassword &&thiscleanedDataconfirmPassword &&thiscleanedDatapassword != thiscleanedDataconfirmPasswordthrow formsValidationError'Passwords do not match.'