Advertisement
Guest User

Untitled

a guest
Aug 30th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. state = {
  2. user: {
  3. name: "",
  4. username: "",
  5. email: "",
  6. password: ""
  7. },
  8. errors: {
  9. name: "",
  10. username: "",
  11. email: "",
  12. password: ""
  13. }
  14. };
  15.  
  16. onFieldChange = e => {
  17. let { user } = this.state;
  18.  
  19. const fieldName = e.target.name;
  20. const fieldValue = e.target.value;
  21.  
  22. user[fieldName] = fieldValue;
  23.  
  24. this.setState(() => ({ user }));
  25. };
  26.  
  27. handleValidation = () => {
  28. let isValid = true;
  29. let { errors } = this.state;
  30. let { name, username, email, password } = this.state.user;
  31. const errMsg = "You cannot leave this empty";
  32.  
  33. if (name === '') {
  34. isValid = false;
  35. errors.name = "You cannot leave this empty";
  36. console.log(name)
  37. }
  38.  
  39. if (typeof name !== "undefined") {
  40. if (!name.match(/^[a-zA-Z]+$/g)) {
  41. isValid = false;
  42. errors.name = "Your name cannot contain numbers";
  43. }
  44. }
  45.  
  46. // Validating the username
  47. if (!username) {
  48. isValid = false;
  49. errors.username = errMsg;
  50. }
  51.  
  52. if (typeof username !== "undefined") {
  53. if (!username.match(/[a-zA-Z0-9]{4, 10}/g)) {
  54. isValid = false;
  55. errors.username =
  56. "Should not be less than 4 or more than 10 characters";
  57. }
  58. }
  59.  
  60. // Validating the email
  61. if (!email) {
  62. isValid = false;
  63. errors.email = errMsg;
  64. }
  65.  
  66. if (typeof email !== "undefined") {
  67. let lastAtPos = email.lastIndexOf("@");
  68. let lastDotPos = email.lastIndexOf(".");
  69.  
  70. if (
  71. !(
  72. lastAtPos < lastDotPos &&
  73. lastAtPos > 0 &&
  74. email.indexOf("@@") == -1 &&
  75. lastDotPos > 2 &&
  76. email.length - lastDotPos > 2
  77. )
  78. ) {
  79. isValid = false;
  80. errors.email = "Email is not valid";
  81. }
  82. }
  83.  
  84. // Validating password
  85. if (!password) {
  86. isValid = false;
  87. errors.password = errMsg;
  88. }
  89.  
  90. if (typeof password !== "undefined") {
  91. if (!password.match(/[a-zA-Z0-9]{6,14}/g)) {
  92. isValid = false;
  93. errors.password = 'Password should be atleast 6 character long, not over 14 characters and must not include special characters.'
  94. }
  95. }
  96.  
  97. this.setState(() => ({ errors }));
  98. return isValid;
  99. };
  100.  
  101. handleRegister = e => {
  102. e.preventDefault();
  103.  
  104. if (this.handleValidation()) {
  105. console.log('Successfully Registered.')
  106. console.log(this.state.user);
  107. } else {
  108. console.log('Some errors occured')
  109. console.log(this.state.errors)
  110. }
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement