-3

Trying to create a form with pretty simple validation and I'm curious as to two things.

One; how do I check if a form is empty?

Two; on the phone number field how would I only accept numbers in this format:

xxx-xxxx (where X is a number)

Here is what I have done so far:

HTML:

<form onsubmit="return false" method="post" name="myForm">

    <div class="form-block">
       <label>Name: </label>
       <input type="text" name="name" id="name" />
     <span id="name-error" class="error"></span>
</div>

<div class="form-block">
       <label>Phone Number: </label>
       <input type="text" name="phone" id="phone" />
     <span id="phone-error" class="error"></span>
</div>

       <input type="submit" id="mysubmit" name="submit" onclick="validate()" />
</form>

CSS:

 a, p, h1, h2, h3, h4, h5, h6, li, label, span {
   font-family: sans-serif;
 }

 #mysubmit {
   display: block;
   margin-top: 10px;
 }

 span.error {
   color: red;
   font-weight: bold;
 }

 .form-block {
    display: block;
    width: 100%;
    margin: 10px 0;
   }

   label {
     display: inline-block;
    width: 150px;
    text-align: right;
  }

JS:

validate = function() {
    var name = document.getElementById("name").value;
  var phone = document.getElementById("phone").value;

  if(/^[a-zA-Z]*$/.test(name)) {
    document.getElementById("name-error").innerHTML = "Good.";
  } else {
    document.getElementById("name-error").innerHTML = "Invalid. Only letters.";
  }

  if(isNaN(phone)) {
  document.getElementById("phone-error").innerHTML = "Can only contain numbers";  
  } else {
   document.getElementById("phone-error").innerHTML = "Good."; 
  }

};
Greggo
  • 97
  • 1
  • 2
  • 11

1 Answers1

0

You can test if the value of a form element is empty by simply checking for an empty string.

I've already posted something that will help you access and iterate through form fields.

// ES5: a very crude validation check
// your form field elements should share a class in order to collect them all
var formElements = document.querySelectorAll('.your-form-field-class');

// set a flag to keep track of whether you have an empty field
var containsEmptyField = false
    i,
    l = formElements.length;

    for (; i < l; i++) {
       if (formElements[i].value === '') {
        containsEmptyField = true;
        // do something in response to an empty field
        // the break is to stop looping since you've found 
        // a match 
        break;
       }    
   }

// ES6: a very crude validation check
const formElements = document.querySelector('#some-form').elements;
let containsEmptyField = false;
for (let element of formElements) {
   if (element.value === '') {
       containsEmptyField = true;
       break;
   }
}

I haven't tested it properly, but the regex for the phone number, might look something like this:

(/^(\d){3,3}\-(\d){4,4}$/).test(someNumber) 
// returns true if value matches or false if it doesn't