Home > Enterprise >  ValidateForm How to validate and show text when submit button was clicked in JavaScript
ValidateForm How to validate and show text when submit button was clicked in JavaScript

Time:11-23

I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field. I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.

Here is my html code

<form>
        <div class="Form-Item">
          <p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
          <input type="text"id="name">
        </div>
        <div class="Form-Item">
          <p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
          <input type="text" id="number">
        </div>
        <div class="Form-Item">
          <p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
          <input type="email">
        </div>
        <div class="Form-Item">
          <p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
          <textarea id="text"></textarea>
        </div>
        <input type="submit" value="submit">
        <p id="log"></p>

    </form>

Here is my JavaScript code


function validateForm(e) {

  if (typeof e == 'undefined') e = window.event;

  var name = U.$('name');
    var number = U.$('number');
    var email = U.$('email');
    var text = U.$('text');

    var error = false;

  if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
        removeErrorMessage('name');
        addCorrectMessage('name', '✔');
    } else {
        addErrorMessage('name', 'Please enter your name.');
        error = true;
    }

  if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
        removeErrorMessage('number');
        addCorrectMessage('number', '✔');
    } else {
        addErrorMessage('number', 'Please enter your phone number.');
        error = true;
    }

  if (/^[\w.-] @[\w.-] \.[A-Za-z]{2,6}$/.test(email.value)) {
        removeErrorMessage('email');
        addCorrectMessage('email', '✔');
    } else {
        addErrorMessage('email', 'Please enter your email address.');
        error = true;
    }

  
  if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
        removeErrorMessage('text');
        addCorrectMessage('text', '✔');
    } else {
        addErrorMessage('text', 'Please enter your enquiry.');
        error = true;
    }

  if (error) {

  if (e.preventDefault) {
    e.preventDefault();
} else {
    e.returnValue = false;
}
return false;

}



}

CodePudding user response:

Modern Browser support the Constraint Validation API which provides localized error messages.

Using this you can easily perform validation during basic events. For example:

// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
  if (this.checkValidity()) {
    [...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
    event.preventDefault();
    return false;
  }
}

Would print all fields which would've been submitted to the console.

Or on an input field:

<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">

Will add the css class "valid" to the input field parent, if the value is foo or bar.

Show code snippet

.valid {
  border: 1px solid green;
}
.valid::after {
  content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
  <fieldset>
    <label for="newslettermail">E-Mail</label>
    <!-- you could also define a more specific pattern on the email input since email would allow foo@bar as valid mail -->
    <input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
  </fieldset>
  <fieldset>
    <input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
    <label for="newsletterAcceptTos">I accept the Terms of Service</label>
  </fieldset>
  <fieldset>
    <label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
    <input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
  </fieldset>
  <button type="submit" id="submitButton" disabled>Submit</button>
  <button type="submit">Force submit (will show errors on invalid input)</button>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.

$("#myform").submit((e) => {
  e.preventDefault(e);
  
  // Validate name.
  const name = $("#name").val();
  if (name.length === 0) {
    alert("Please provide a name!");
    return;
  }
  
  alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="myform">
  <input type="text" id="name" placeholder="John Doe" />
  <button type="submit">Submit</button>
</form>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

which npm package do u use to validate ur data?.

If u use "validator" (link: https://www.npmjs.com/package/validator) You can check if the field is filled correctly and send a check mark to the user.

for example if u wanted to check if data is an email

const validator = require("validator");

validator.isEmail('[email protected]');

if u want to see more about the options for the field just check the npm package page

  • Related