{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/controlling-and-validating-forms","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Controlling and Validating Forms\",\n  \"order\": 44,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"react\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Controlling and Validating Forms\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Controlled forms\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Validating forms\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Giving UI feedback\")), mdx(\"h2\", null, \"Controlled form\"), mdx(\"p\", null, \"Now that our components are starting to look closer to what we would like, we should tie our form in with the state of our component. When people first start using Redux, they have a habit of tying everything into \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \". But just because you have the global \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \" doesn't mean that everything belongs there. Or as Redux founder Dan Abramov said:\"), mdx(\"blockquote\", null, mdx(\"p\", {\n    \"parentName\": \"blockquote\"\n  }, \"You don't need a single source of truth for \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"everything\"), \". Just make sure you have a single source of truth for any particular thing.\")), mdx(\"p\", null, \"A form like a signup or login form is a good example of transitory data that does not need to be saved in your Redux \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"store\"), \". If a user navigates away and comes back, does he expect that Redux would remember the status of that form? Probably not. In fact, she would probably think it's weird.\"), mdx(\"p\", null, \"It is for this reason that our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Signup\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" components will have their values tied to local \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \". First we should set the initial values of our form state.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nexport class Signup extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      username: \\\"\\\",\\n      email: \\\"\\\",\\n      password: \\\"\\\",\\n      passwordVerify: \\\"\\\"\\n    }\\n    this.submit = this.submit.bind(this)\\n  }\\n  ...\\n}\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\nexport class Login extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      email: \\\"\\\",\\n      password: \\\"\\\"\\n    }\\n  }\\n  ...\\n}\\n\")), mdx(\"h2\", null, \"Update Login component\"), mdx(\"p\", null, \"Then we need three more things. We need a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handleChange\"), \" function (or whatever you prefer to name it) that will update our state based on the input, we need to set the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"value\"), \" of each input to the value of the corresponding state value, and we need to change the values that we submit to our new state values.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export class Login extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      email: \\\"\\\",\\n      password: \\\"\\\",\\n    }\\n    this.submit = this.submit.bind(this)\\n  }\\n\\n  submit() {\\n    const user = {\\n      email: this.state.email,\\n      password: this.state.password,\\n    }\\n    this.props.dispatch(Actions.userLogin(user))\\n  }\\n\\n  handleChange(input, e) {\\n    this.setState({ [input]: e.target.value })\\n  }\\n\\n  render() {\\n    return (\\n      <div className={style.wrapper}>\\n        <div className={style.form}>\\n          <div className={style.inputGroup}>\\n            <input\\n              value={this.state.email}\\n              onChange={e => {\\n                this.handleChange(\\\"email\\\", e)\\n              }}\\n              placeholder=\\\"Email\\\"\\n              className={style.input}\\n              type=\\\"text\\\"\\n            />\\n          </div>\\n          <div className={style.inputGroup}>\\n            <input\\n              value={this.state.password}\\n              onChange={e => {\\n                this.handleChange(\\\"password\\\", e)\\n              }}\\n              placeholder=\\\"Password\\\"\\n              className={style.input}\\n              type=\\\"password\\\"\\n            />\\n          </div>\\n          <Button onClick={this.submit} _style={{ width: \\\"100%\\\" }} type=\\\"primary\\\">\\n            Submit\\n          </Button>\\n        </div>\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"So now, when you type something into the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"input\"), \" field, it triggers the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"onChange\"), \" function, which in turn triggers the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.handleChange\"), \" function that we defined. Within that function, we set the local \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"state\"), \" of the relevant input to the value of the input, which is also tied to the relevant \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"this.state[value]\"), \". We've provided a handy chart showing the general flow of controlled forms below.\"), mdx(\"p\", null, \"TODO image on form flow in React\\n\", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"Handy chart coming soon\")), mdx(\"p\", null, \"This might sound like a roundabout way of filling out forms, and that's because it is. But there are advantages of doing it this way (as you will see shortly).\"), mdx(\"h2\", null, \"Update Signup component\"), mdx(\"p\", null, \"One things users have come to expect from forms is immediate feedback as to the validity of their form inputs because it's annoying to fill out an entire form only to submit the form and have an error telling you that it's invalid (especially when it then erases all existing form data, which many websites do for some reason).\"), mdx(\"p\", null, \"Let's start by updating our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Signup\"), \" component to use a controlled form just like our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Login\"), \" component above.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"export class Signup extends React.Component {\\n  constructor(props) {\\n    super(props)\\n    this.state = {\\n      username: \\\"\\\",\\n      email: \\\"\\\",\\n      password: \\\"\\\",\\n      passwordVerify: \\\"\\\",\\n    }\\n    this.submit = this.submit.bind(this)\\n  }\\n\\n  submit() {\\n    const user = {\\n      username: this.state.username,\\n      email: this.state.email,\\n      password: this.state.password,\\n    }\\n    this.props.dispatch(Actions.userNew(user))\\n  }\\n\\n  handleChange(input, e) {\\n    this.setState({ [input]: e.target.value })\\n  }\\n\\n  render() {\\n    return (\\n      <div className={style.wrapper}>\\n        <div className={style.form}>\\n          <div className={style.inputGroup}>\\n            <input\\n              onChange={e => {\\n                this.handleChange(\\\"username\\\", e)\\n              }}\\n              value={this.state.username}\\n              placeholder=\\\"Username\\\"\\n              className={style.input}\\n              type=\\\"text\\\"\\n            />\\n          </div>\\n          <div className={style.inputGroup}>\\n            <input\\n              onChange={e => {\\n                this.handleChange(\\\"email\\\", e)\\n              }}\\n              value={this.state.email}\\n              placeholder=\\\"Email\\\"\\n              className={style.input}\\n              type=\\\"text\\\"\\n            />\\n          </div>\\n          <div className={style.inputGroup}>\\n            <input\\n              onChange={e => {\\n                this.handleChange(\\\"password\\\", e)\\n              }}\\n              value={this.state.password}\\n              placeholder=\\\"Password\\\"\\n              className={style.input}\\n              type=\\\"password\\\"\\n            />\\n          </div>\\n          <div className={style.inputGroup}>\\n            <input\\n              onChange={e => {\\n                this.handleChange(\\\"passwordVerify\\\", e)\\n              }}\\n              value={this.state.passwordVerify}\\n              placeholder=\\\"Verify Password\\\"\\n              className={style.input}\\n              type=\\\"password\\\"\\n            />\\n          </div>\\n          <Button onClick={this.submit} _style={{ width: \\\"100%\\\" }} type=\\\"primary\\\">\\n            Submit\\n          </Button>\\n        </div>\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"And now that we have a controlled form, we can use the values we received to validate our inputs before a user submits them. We're going to create two validations to make it easy for a user to know in advance whether the email address they entered is valid and whether the password match.\"), mdx(\"p\", null, \"We'll start by creating valid and invalid constants that we can use as out inline style objects. If valid, the input will receive a green underline; if invalid, it will receive a red underline.\"), mdx(\"p\", null, \"The first function is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validatePassword\"), \", which compares the current state of our passwords and returns invalid if less than 6 characters or when the passwords don't match. It returns valid when the password are at least 6 characters and match.\"), mdx(\"p\", null, \"The second is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"validateEmail\"), \", which uses a regular expression to make sure the email address contains an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@\"), \" symbol, which is a bit oversimplified, but it servers our purposes.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nconst validInput = { borderBottom: \\\"3px solid #4CAF50\\\" }\\nconst invalidInput = { borderBottom: \\\"3px solid #F44336\\\" }\\n\\nexport class Signup extends React.Component {\\n...\\n\\n  validateEmail() {\\n    if (this.state.email.length < 1) return {}\\n    return /@/.test(this.state.email) ? validInput : invalidInput\\n  }\\n\\n  validatePassword() {\\n    if (this.state.password.length < 1) return {}\\n    if (this.state.password.length < 6) return invalidInput\\n    return this.state.password === this.state.passwordVerify ? validInput : invalidInput\\n  }\\n\\n...\\n}\\n\\n\")), mdx(\"p\", null, \"Then we need to connect these functions to our inputs. We're going to add a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"style\"), \" tag to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"email\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"passwordVerify\"), \" inputs, and in that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"style\"), \" tag we call the relevant function to validate. Note that in the event of no match (in both cases, if length is greater than 1), we're returning an empty object.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-js\",\n    \"parentName\": \"pre\"\n  }, \"...\\n\\nexport class Signup extends React.Component {\\n  ...\\n\\n  render() {\\n\\n    return (\\n      <div className={style.wrapper}>\\n        <div className={style.form}>\\n          ...\\n          <div className={style.inputGroup}>\\n            <input\\n              onChange={e => { this.handleChange(\\\"email\\\", e) }}\\n              style={this.validateEmail()}\\n              value={this.state.email}\\n              placeholder=\\\"Email\\\"\\n              className={style.input}\\n              type=\\\"text\\\" />\\n          </div>\\n          ...\\n          <div className={style.inputGroup}>\\n            <input\\n              onChange={e => { this.handleChange(\\\"passwordVerify\\\", e) }}\\n              style={this.validatePassword()}\\n              value={this.state.passwordVerify}\\n              placeholder=\\\"Verify Password\\\"\\n              className={style.input}\\n              type=\\\"password\\\" />\\n          </div>\\n        </div>\\n      </div>\\n    )\\n  }\\n}\\n\")), mdx(\"p\", null, \"And now you have form validation. As you can see, React's inline styling makes this really easy.\"), mdx(\"p\", null, \"Create validation endpoint to check if username/email is taken?\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Controlling and Validating Forms Controlled forms Validating forms Giving UI feedback Controlled form Now that our components are starting…","frontmatter":{"title":"Controlling and Validating Forms","order":44,"active":true,"free":false,"tech":["react"]}}},"pageContext":{"slug":"controlling-and-validating-forms","prevNode":{"frontmatter":{"title":"CRUD Endpoints for Organization: Part 1","active":true,"free":false,"order":43,"tech":["phoenix"]},"fields":{"slug":"crud-endpoints-for-organization-part-1"}},"nextNode":{"frontmatter":{"title":"CRUD Endpoints for Organization: Part 2","active":true,"free":false,"order":44,"tech":["phoenix"]},"fields":{"slug":"crud-endpoints-for-organization-part-2"}}}},"staticQueryHashes":["1723017916"]}