0

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>

10
  • 2
    Can you share the HTML too? Commented Jun 9, 2019 at 16:14
  • After getting the value of the input you then can "will i ever" !== value.slice(0, 11) Commented Jun 9, 2019 at 16:22
  • first of all, I think your quotation marks are placed wrong. The code example shows red text where it thinks it's a string, but you write an if statement. Commented Jun 9, 2019 at 16:24
  • "text" or 'text' is better than `text`. Because the ` mark is used a lot in MySQL or here as a code markup. Commented Jun 9, 2019 at 16:25
  • the problem begins at: //$form.querySelector(.error).innerHTML = `Some errors occurred`; Commented Jun 9, 2019 at 16:28

3 Answers 3

2

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')?

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for that notice, the original validation was for multiple input fields, i only use 1 input field here. Forgot to change that.
@ArthurRobaeys Huh? The issue is with class selectors (.input) vs. tag selectors (input), not multiple fields.
Yes, indeed. In this case i should've changed it to .querySelector('.question_field'). The line you selected was a line i forgot to edit.
I edited the line, and now right before i click submit with a value that's totally random, the error message quickly shows up before submitting the form anyway. So it seems the if statement for the input starting with:'Will i ever' works, but it submits anyways.
1

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>

Comments

0

You have uncommented backtick at occured `;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.