Guest User

Untitled

a guest
Nov 30th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.93 KB | None | 0 0
  1. # Validators
  2.  
  3. ```js
  4. const validator = {
  5. username: {
  6. rules: [
  7. {
  8. test: /^[a-z0-9_]+$/,
  9. message: 'Username must contain only alphabets-numeric lowercase characters',
  10. },
  11. {
  12. test: (value) => {
  13. return value.length > 2;
  14. },
  15. message: 'Username must be longer than two characters',
  16. },
  17. ],
  18. errors: [],
  19. valid: false,
  20. state: '',
  21. },
  22. password: {
  23. rules: [
  24. {
  25. test: (value) => {
  26. return value.length >= 6;
  27. },
  28. message: 'Password must not be shorter than 6 characters',
  29. },
  30. ],
  31. errors: [],
  32. valid: false,
  33. state: ''
  34. },
  35. };
  36.  
  37. export default validator;
  38. ```
  39.  
  40. # Validator Implementation
  41.  
  42. ```js
  43. import React, { Component } from 'react';
  44. import validators from './validators';
  45.  
  46. export default class Signin extends Component {
  47. constructor() {
  48. super();
  49.  
  50. this.state = {
  51. userInfo: {
  52. username: '',
  53. password: '',
  54. }
  55. };
  56.  
  57. // Set of validators for signin form
  58. this.validators = validators;
  59.  
  60. // This resets our form when navigating between views
  61. this.resetValidators();
  62.  
  63. // Correctly Bind class methods to reacts class instance
  64. this.handleInputChange = this.handleInputChange.bind(this);
  65. this.displayValidationErrors = this.displayValidationErrors.bind(this);
  66. this.updateValidators = this.updateValidators.bind(this);
  67. this.resetValidators = this.resetValidators.bind(this);
  68. this.handleSubmit = this.handleSubmit.bind(this);
  69. this.isFormValid = this.isFormValid.bind(this);
  70. }
  71.  
  72. /**
  73. * This function is called whenever a form input is changed
  74. * Which in turn updates the state of this component and validators
  75. */
  76. handleInputChange(event, inputPropName) {
  77. const newState = Object.assign({}, this.state);
  78. newState.userInfo[inputPropName] = event.target.value;
  79. this.setState(newState);
  80. this.updateValidators(inputPropName, event.target.value);
  81. }
  82.  
  83. /**
  84. * This function handles the logic when submiting the form.
  85. * @TODO make an API request to authenticate the user
  86. */
  87. handleSubmit(e) {
  88. console.log(this.state.userInfo);
  89. console.log('Yepee! form submitted');
  90. e.preventDefault();
  91. }
  92.  
  93. /**
  94. * This function updates the state of the validator for the specified validator
  95. */
  96. updateValidators(fieldName, value) {
  97. this.validators[fieldName].errors = [];
  98. this.validators[fieldName].state = value;
  99. this.validators[fieldName].valid = true;
  100. this.validators[fieldName].rules.forEach((rule) => {
  101. if (rule.test instanceof RegExp) {
  102. if (!rule.test.test(value)) {
  103. this.validators[fieldName].errors.push(rule.message);
  104. this.validators[fieldName].valid = false;
  105. }
  106. } else if (typeof rule.test === 'function') {
  107. if (!rule.test(value)) {
  108. this.validators[fieldName].errors.push(rule.message);
  109. this.validators[fieldName].valid = false;
  110. }
  111. }
  112. });
  113. }
  114.  
  115. // This function resets all validators for this form to the default state
  116. resetValidators() {
  117. Object.keys(this.validators).forEach((fieldName) => {
  118. this.validators[fieldName].errors = [];
  119. this.validators[fieldName].state = '';
  120. this.validators[fieldName].valid = false;
  121. });
  122. }
  123.  
  124. // This function displays the validation errors for a given input field
  125. displayValidationErrors(fieldName) {
  126. const validator = this.validators[fieldName];
  127. const result = '';
  128. if (validator && !validator.valid) {
  129. const errors = validator.errors.map((info, index) => {
  130. return <span className="error" key={index}>* {info}</span>;
  131. });
  132.  
  133. return (
  134. <div className="col s12 row">
  135. {errors}
  136. </div>
  137. );
  138. }
  139. return result;
  140. }
  141.  
  142. // This method checks to see if the validity of all validators are true
  143. isFormValid() {
  144. let status = true;
  145. Object.keys(this.validators).forEach((field) => {
  146. if (!this.validators[field].valid) {
  147. status = false;
  148. }
  149. });
  150. return status;
  151. }
  152.  
  153. // Renders the template
  154. render() {
  155. return (
  156. <div className="row">
  157. <div className="col s12 m8 l4 offset-m2 offset-l4 z-depth-4 card-panel login-form">
  158. <form className="col s12" onSubmit={this.handleSubmit}>
  159. <div className="row">
  160. <div className="input-field col s12">
  161. <h4 className="center login-form-text">Sign into your account</h4>
  162. </div>
  163. </div>
  164. <div className="row margin">
  165. <div className="input-field col s12">
  166. <i className="material-icons prefix">person</i>
  167. <input
  168. id="username"
  169. type="text"
  170. value={this.state.userInfo.username}
  171. onChange={event => this.handleInputChange(event, 'username')}
  172. />
  173. <label htmlFor="username" className="left-align">username</label>
  174. </div>
  175. { this.displayValidationErrors('username') }
  176. </div>
  177. <div className="row margin">
  178. <div className="input-field col s12">
  179. <i className="material-icons prefix">lock</i>
  180. <input
  181. id="password"
  182. type="password"
  183. value={this.state.userInfo.password}
  184. onChange={event => this.handleInputChange(event, 'password')}
  185. />
  186. <label htmlFor="password" className="left-align">Password</label>
  187. </div>
  188. { this.displayValidationErrors('password') }
  189. </div>
  190. <div className="row">
  191. <div className="input-field col s12 signup-btn">
  192. <button className={`btn waves-effect waves-light col s12 ${this.isFormValid() ? '' : 'disabled'}`}>
  193. Login
  194. </button>
  195. </div>
  196. </div>
  197. </form>
  198. </div>
  199. </div>
  200. );
  201. }
  202. }
  203. ```
Add Comment
Please, Sign In to add comment