Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Test if field is EMPTY and NOT a number

I am a beginner JS student and attempting to do some form validation and I am struggling with it. I am currently suffering from covid so my brain may not be functioning and thinking through this properly but I need some help.

Basically what I am trying to test is that the "name" field of my form isn't blank AND that a number has not been input. I can get the blank part to check just fine but the number part is throwing me off. Here is the code I am working with.

function validateForm() {
  let x = document.forms["contact_form"]["myName"].value;
  if ((x == "") && (typeof x == 'number')) {
    alert("Name must be filled out properly.");
    return false;
  }

}

Following suggestions.. It would seem I am not accessing form data properly. Here is the form data I am attempting to access:

<form class="contact_form" method="put" action="confirmation.html">
    <label for="myName">Name:</label>
    <input type="text" name="myName" id="myName" required />

Thank you for any and all help!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Since you are using &&, condition is guaranteed to evaluate false. You should use OR (||) operator here.

Also, the the type of the value of x is string always string, you have to cast the value to number before the comparison, you can do so by prefixing + to the variable:

if ((x == "") || (typeof +x == 'number')) {

Though, I will suggest you to use use isNaN()

if ((x == "") || !isNaN(x)) {

Demo:

function validateForm() {
  let x = document.forms["contact_form"]["myName"].value;
  if ((x == "") || !isNaN(x)) {
    alert("Name must be filled out properly.");
    return false;
  }

}
<form name="contact_form">
  <input name="myName">
  <button onclick="return validateForm()">Click</button>
</form>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!