Advertisement
ProfWendi

Quick Client Side Reg Form Validation

Jul 20th, 2021 (edited)
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. "use strict";
  2.  
  3. /* Wendi Jollymore
  4.    syst10199, Feb 2016
  5.    modified for prog32758, Aug 2020
  6.    updated to latest ES5 July 2021
  7.    some validation for a registration form
  8.  
  9. Feel free to modify.
  10. */
  11.  
  12. // unobtrusive javascript!!!
  13. document.addEventListener("DOMContentLoaded", init);
  14. function init() {
  15.     document.querySelector("form input[type=submit]").addEventListener("click", validator);
  16. }
  17.  
  18. // not very reusable validation, but done quickly
  19.  
  20. // TODO: check password strength!!
  21.  
  22. let validator = {
  23.     handleEvent(event) {
  24.         let form = event.target.form;
  25.        
  26.         // in case browser doesn't support html5 constraint validation
  27.         // (can test by removing required attribute)
  28.         //checkEmpty(form.email, "Email", div);
  29.         //checkEmpty(form.pass, "Password", div);
  30.         //checkEmpty(form.verify, "Verify Password", div);
  31.    
  32.         // password must match verify password field
  33.         if (form.pass.value !== form.verify.value) {
  34.             form.verify.setCustomValidity("Passwords don't match.");
  35.             form.verify.reportValidity();  // report to browser
  36.         } else {
  37.             // cancel/undo verify validity
  38.             form.verify.setCustomValidity("");
  39.            
  40.             // in case browser doesn't support pattern="" attribute
  41.             let emailPatt = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  42.             if (!emailPatt.test(form.email.value.toLowerCase())) {
  43.                 form.email.setCustomValidity("Invalid email format.");
  44.                 form.email.reportValidity();  // report to browser
  45.             } else {
  46.                 // cancel/undo email validity
  47.                 form.email.setCustomValidity("");  
  48.             }          
  49.         }
  50.        
  51.         // don't submit if there are any errors
  52.         if (!form.checkValidity()) {
  53.             event.preventDefault();
  54.         }
  55.     }
  56.    
  57. };
  58.  
  59. // determines if an input field is empty and reports error if it is
  60. function checkEmpty(field, fieldName) {
  61.     if (field.value == null || field.value == "") {
  62.         field.setCustomValidity(fieldName + " can't be empty.");
  63.         field.reportValidity();
  64.     } else {
  65.         field.setCustomValidity("");
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement