2021年4月25日星期日

JavaScript form validation but: the invalid email error message is never displayed

I am working on a form validator class in JavaScript.

First, I check (make sure) that all required fields are filled. If they are, I validate the email format:

class FormValidator {    constructor() {      this.hasErrors = false;      this.emptyRequired = [];      this.errorMsg = "";          this.formToValidate = document.querySelector("form");      this.submitButton = this.formToValidate.querySelector("input[type=submit]");      }        appendErrorMessage(){      const errorEl = `<span class="error-message">${this.errorMsg}</span>`;      this.emptyRequired.forEach((field) => {         let parentEl = field.parentElement;         if(this.hasErrors == true && parentEl.querySelectorAll('.error-message').length == 0) {          field.insertAdjacentHTML('afterend', errorEl);         }      });    }        validateEmail() {        this.hasErrors = false;        const re = /^(([^<>()[\]\\.,;:\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,}))$/;        const emailFiled = this.formToValidate.querySelector('input[type=email]');        if (this.emptyRequired.length == 0) {          const action = re.test(emailFiled) ? 'remove' : 'add';          emailFiled.classList[action]('is-invalid');                    this.hasErrors = re.test(emailFiled) ? false : true;          this.errorMsg = "Please provide a valid email";          this.appendErrorMessage();        }            }        validateRequired() {        this.hasErrors = false;        this.emptyRequired = [];        const requiredFields = this.formToValidate.querySelectorAll('*[required]');        requiredFields.forEach((field) => {          // Make sure all required fields have values          // Before doing other validations          if(!field.value) {             this.hasErrors = true;             this.emptyRequired.push(field);             this.errorMsg = "This field is required";             this.appendErrorMessage();          }          const action = field.value ? 'remove' : 'add';          field.classList[action]('is-invalid');      });    }        validateForm() {      this.validateRequired();      this.validateEmail();      console.log(this.errorMsg);    }        submitForm(e) {      e.preventDefault();      this.validateForm();    }        init() {      this.formToValidate.addEventListener('submit', e => this.submitForm(e));    }  }    const formValidator = new FormValidator();  formValidator.init();
.form-group {    position: relative;  }    .error-message {      margin: 0;      position: absolute;      right: 5px;      bottom: -13px;      color: #a94442;      font-size: 11px;  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>  <div class="container">    <div class="card my-3">      <div class="card-header">Contact us</div>      <div class="card-body">        <form action="/" novalidate>          <div class="form-group">            <input type="text" name="name" class="form-control" placeholder="Your Name" value="" required />          </div>          <div class="form-group">            <input type="email" name="email" class="form-control" placeholder="Your Email" value="" required />          </div>          <div class="form-group">            <input type="text" name="phone" class="form-control" placeholder="Your Phone Number" value="" required />          </div>          <div class="form-group">            <textarea name="message" class="form-control" placeholder="Your Message"></textarea>          </div>          <div class="form-group mb-0">            <input type="submit" name="btnSubmit" class="btn btn-success btn-block" value="Send Message" />          </div>        </form>      </div>    </div>  </div>

The problem

I filled all the form fields, including the email. The email I provided is invalid.

For a reason I have not been able to figure out, the message Please provide a valid email is never appended to the <div class="form-group">.

enter image description here

https://stackoverflow.com/questions/67256995/javascript-form-validation-but-the-invalid-email-error-message-is-never-display April 26, 2021 at 02:38AM

没有评论:

发表评论