skip to Main Content

I’ve been working on anocode design studio landing page, and I’m currently tackling the phone number validation. I want to make sure that only numbers are accepted in the phone number field. Here’s the part of the code I’ve been working on for this. Any tips or suggestions would be appreciated!

Feel free to provide more details or ask for specific assistance if needed!

I need solution by Javascript only.

<form id="enquiryForm" name="wf-form-Enquiry-Form-2" data-name="Enquiry Form" >
    <input type="text" class="form-input-field w-input" maxlength="256" name="Name" data-name="Name" placeholder="Name*" id="name" required="">
    <input type="email" class="form-input-field w-input" maxlength="256" name="Email" data-name="Email" placeholder="Email*" id="Email" required="">
    <input type="text" class="form-input-field w-input" maxlength="256" name="Company" data-name="Company" placeholder="Company*" id="Company" required="">
    <input type="text" class="form-input-field w-input" maxlength="256" name="Phone" data-name="Phone" placeholder="Phone" id="Phone" required="">
    <textarea id="Project-Detail" name="Project-Detail" maxlength="5000" data-name="Project Detail" placeholder="Tell us about your project" class="form-input-field text-area w-input"></textarea>
    <div class="w-embed">
        <input type="hidden" class="button-position" name="Position" value="">
    </div>
    <input type="submit" value="Book Free Call" data-wait="Please wait..." class="button red-btn form w-button">
</form>

2

Answers


  1. Target the input type like this

    const phoneInput = document.getElementById('Phone');
    

    Now Create a function for this. This will check regex exp.

    function validatePhoneNumber(phoneNumber) {
      const phoneRegex = /^d+$/;
      return phoneRegex.test(phoneNumber);
    }
    

    Now create an event to detect the input number.

    phoneInput.addEventListener('keyup', function (event) {
      // Get phone number
      const phoneNumber = event.target.value;
    
      // Validate number
      const isValid = validatePhoneNumber(phoneNumber);
    
      // Check validation
      if (!isValid) {
        console.log('Please enter a valid phone number.');
      } else {
        phoneInput.setCustomValidity('');
      }
    });
    
    Login or Signup to reply.
  2. this would be helpful for you:

    <input type="text" id="phoneNumber" oninput="validateNumber(this)">
    

    Script:

    function validateNumber(input) {
      // Remove non-numeric characters from the input value
      let cleanedValue = input.value.replace(/D/g, '');
    
      // Update the input value with the cleaned value
      input.value = cleanedValue;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search