Arthur Robaeys
Arthur Robaeys

Reputation: 355

Having issues with validation of input field

I'm trying to validate an input field. When i try to submit without filling in something, it gives me the error i made: please start your question with: will i ever. So i'm trying to check wether the text that the user types into the field, starts with: will i ever.

However, when i type a single (or more) random character(s), it just submits the form. I want it to check if the input starts with those fixed tree words, otherwise, no submission.

{
  const handleSubmitForm = e => {
  const $form = e.currentTarget;
  if (!$form.checkValidity()) {
    e.preventDefault();

    const field = $form.querySelector('.question_field');
    showValidationInfo(field);

    //$form.querySelector('.error').innerHTML = 'Some errors occured';
  } else {
    console.log('Form is valid => submit form');
  }
};

const showValidationInfo = field => {
  console.log(field);
  let message;
  if (field.validity.valueMissing) {
    message = 'Please fill in a question starting with: Will i ever';
  }
  if (field.validity.typeMismatch) {
    message = 'Type not right';
  }
  if (field.validity.rangeOverflow) {
    const max = field.getAttribute('max');
    message = 'Too big, max ${max}';
  }
  if (field.validity.rangeUnderflow) {
    const min = field.getAttribute('min');
    message = 'Too small, min ${min}';
  }
  if (field.validity.tooShort) {
    const min = field.getAttribute('minlength');
    message = 'Too short, minimum length is ${min}';
  }
  if (field.validity.tooLong) {
    const max = field.getAttribute('maxlength');
    message = 'Too long, maximum length is ${max}';
  }
  if (!field.value.toLowerCase().startsWith("will i ever")) {
    message = 'Start your question with: Will i ever';
  }
  if (message) {
    field.parentElement.querySelector('.error').textContent = 
   message;
    field.parentElement.querySelector('.error').style.color = "red";
  }
};

const handeInputField = e => {
  const $field = e.currentTarget;
  if ($field.checkValidity()) {
    $field.parentElement.querySelector('.error').textContent = '';
    if ($field.form.checkValidity()) {
      $field.form.querySelector('.error').innerHTML = '';
    }
  }
};

const handeBlurField = e => {
  const $field = e.currentTarget;
  showValidationInfo($field);
};

const addValidationListeners = fields => {
  fields.forEach($field => {
    $field.addEventListener('input', handeInputField);
    $field.addEventListener('blur', handeBlurField);
  });
};

const init = () => {
  const $form = document.querySelector('form');
  $form.noValidate = true;
  $form.addEventListener('submit', handleSubmitForm);

  const fields = $form.querySelectorAll('.input');
  addValidationListeners(fields);
};

init();
}
<div class="name_wrapper">
  <form autocomplete="off" class="form_question" action="answer.html">
    <label class="name question" for="name">Ask me a question</label>
    <div class="question_wrapper">
      <p class="error">Start your question with: Will i ever...</p>
      <input class="field question_field" type="text" name="question" placeholder="Will i ever..." value="" required>
    </div>
    <input id="button" class="answr-btn btn-question" type="submit" value="answer it!">
    <input autocomplete="false" name="hidden" type="text" style="display:none;">
  </form>
</div>

Upvotes: 0

Views: 336

Answers (3)

ramirozap
ramirozap

Reputation: 1459

The problem is how you are handling the validation, the key is in this line if (!$form.checkValidity()) { this will not check if your string starts with Will i ever you have to do it manually before the if, here you have an alternative solution:

{
 const handleSubmitForm = e => {
  
  const $form = e.currentTarget;
  const field = $form.querySelector('.question_field');
  //here we validate the form manually
  const message = showValidationInfo(field);
  //if a message is found we show the error on the DOM, if is undefined we have no errors and we can submit the form
  if (message) {
    e.preventDefault();

  $form.querySelector('.error').innerHTML = message;
  $form.querySelector('.error').style.color = "red";
} else {
  console.log('Form is valid => submit form');
}
 };

const showValidationInfo = field => {
  if (field.validity.valueMissing) {
    return 'Please fill in a question starting with: Will i ever';
  }
  if (field.validity.typeMismatch) {
    return 'Type not right';
  }
  if (field.validity.rangeOverflow) {
    const max = field.getAttribute('max');
    return 'Too big, max ${max}';
  }
  if (field.validity.rangeUnderflow) {
    const min = field.getAttribute('min');
    return 'Too small, min ${min}';
  }
  if (field.validity.tooShort) {
    const min = field.getAttribute('minlength');
    return 'Too short, minimum length is ${min}';
  }
  if (field.validity.tooLong) {
    const max = field.getAttribute('maxlength');
    return 'Too long, maximum length is ${max}';
  }
  if (!field.value.toLowerCase().startsWith("will i ever")) {
    return 'Start your question with: Will i ever';
  }

  return undefined;
};

const handeInputField = e => {
const $field = e.currentTarget;
if ($field.checkValidity()) {
  $field.parentElement.querySelector('.error').textContent = '';
  if ($field.form.checkValidity()) {
    $field.form.querySelector('.error').innerHTML = '';
  }
}
};

const handeBlurField = e => {
const $field = e.currentTarget;
showValidationInfo($field);
};

const addValidationListeners = fields => {
fields.forEach($field => {
  $field.addEventListener('input', handeInputField);
  $field.addEventListener('blur', handeBlurField);
});
};

const init = () => {
const $form = document.querySelector('form');
$form.noValidate = true;
$form.addEventListener('submit', handleSubmitForm);

const fields = $form.querySelectorAll('.input');
addValidationListeners(fields);
};

init();
}
<div class="name_wrapper">
        <form autocomplete="off" class="form_question" action="answer.html">
            <label class="name question" for="name">Ask me a question</label>
            <div class="question_wrapper">
            <p class="error">Start your question with: Will i ever...</p>
                <input class="field question_field" type="text" name="question" placeholder="Will i ever..." value="" required>
            </div>
            <input id="button" class="answr-btn btn-question" type="submit" value="answer it!">
            <input autocomplete="false" name="hidden" type="text" style="display:none;">
        </form>

Upvotes: 1

Tony Okoth
Tony Okoth

Reputation: 157

You have uncommented backtick at occured `;

Upvotes: 0

melpomene
melpomene

Reputation: 85867

This line makes no sense:

const fields = $form.querySelectorAll('.input');

There are no HTML elements with class="input" in your form.

Did you mean $form.querySelectorAll('input')?

Upvotes: 2

Related Questions