5

I'm building a multipage form and I have some unusual validation requirements. Here's what I'd like to do/what I have done so far.

What I Want to Do:

(1) As each form field is filled in, I want a function to run and check that the user-input has met certain conditions -- i.e. for first and last name, that there are no numbers and there is a space in between the names.

(2) Once each of the field are full and have passed as true, I want another function to run that re-enabled a previously disabled "Next" button that will move the user to the next page of the form.

What I Have Done

(1) Created a mini version of the form with two inputs:

  1. One that takes a first name, a space and a last name
  2. One that takes a phone number set up the following way xxx xxx xxx

(2) I've console.logged the results with pass/fail logic so I know when certain things are being input by the user, that the code is validating properly.

Where I am Stuck:

I do not know how to create the secondary code that will reenabled the previously disabled "next" button that will move the form to the next page.

What I would like to do is make it so when the "Next" button is reenabled, and clicked on, it's own onclick function hides the current page, looks for the next page in the sequence and changes its display:block and I believe I have that code worked out separately, but I don't know how to integrate it with my other needs.

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

	
	function checkFirstName()
	{
		if(firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
	{
		console.log("Put a first Name and Last Name");
	}
	else
	{
		console.log("Thank You");
	}

	};
	
	checkFirstName();
	
	function checkPhoneNumber()
	{
		if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/))
			 {
			 console.log("Please Put in a proper phone number");
			 }
	else
	{
		console.log("Thank you");
		cansubmit = true;
	}
	};
	checkPhoneNumber();
	
};


	
<form>
First Name: <input type="text" id="name" onblur="checkForm()" /><label id="nameErrorPrompt"></label>
	<br />

	Phone Number: <input type="text" id="phone" onblur="checkForm()" /><label></label>
	<br />
	
	<button id="myButton" disabled="disabled">Test Me</button>
</form>

3 Answers 3

3

See below code.

It might be more user-friendly to use on keyup rather than onblur, as most users I know will try and click the disabled button, rather than pressing tab or focusing on another element.

function checkForm() {
  var firstName = document.getElementById("name").value;

  var phone = document.getElementById("phone").value;

  var phoneCanSubmit, nameCanSubmit = false;

  function checkFirstName() {
    if (firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
      nameCanSubmit = false;
      console.log("Put a first Name and Last Name");
    } else {
      nameCanSubmit = true;
      console.log("Thank You");
    }

  };

  checkFirstName();

  function checkPhoneNumber() {
    if (!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
      phoneCanSubmit = false;
      console.log("Please Put in a proper phone number");
    } else {
      phoneCanSubmit = true;
      console.log("Thank you");
      cansubmit = true;
    }
  };
  checkPhoneNumber();
  if (nameCanSubmit && phoneCanSubmit) {
    document.getElementById("myButton").disabled = false;
  } else {
    document.getElementById("myButton").disabled = true;
  }
};
<form>
  First Name:
  <input type="text" id="name" onblur="checkForm()" />
  <label id="nameErrorPrompt"></label>
  <br />Phone Number:
  <input type="text" id="phone" onblur="checkForm()" />
  <label></label>
  <br />

  <button id="myButton" disabled="disabled">Test Me</button>
</form>

2

The code below gives you what you want. I removed some extraneous checks to simplify the code and also moved the event handlers from he HTML to the JavaScript. I also pulled the field checks out of the larger checkForm function. This provides you the flexibility to use them one at at time if need be.

window.addEventListener('load', function(e) {
    var nameInput = document.getElementById('name');
    var phoneInput = document.getElementById('phone');
    var myButton = document.getElementById('myButton');

     myButton.addEventListener('click', function(e) {
        e.preventDefault(); //Stop the page from refreshing
         getNextPage('Next page shown!!');
    }, false);

    nameInput.addEventListener('blur', function(e) {
        checkName(this.value);
    }, false);

    phoneInput.addEventListener('blur', function(e) {
        //Uncomment below to make this responsible only for checking the phone input
        //checkPhoneNumber(this.value);
        /*You could do away with diasbling and check the form 
        on submit, but if you want to keep the disable logic
        check the whole form on the blur of the last item*/
        checkForm();
    }, false);
}, false);

function getNextPage(foo) {
    console.log('Callback fired: ', foo);
    //Do something here
}

function checkPhoneNumber(phone) {
    if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
         console.log("Please Put in a proper phone number");
        return 0;
    }
    else {
        console.log("Thank you name entered");
        return 1;
    }
};

//Removed a bit of over coding, no ned to check isNaN or empty string since using regex already
function checkName(firstAndLastName) {
    if(!firstAndLastName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
        console.log("Put a first Name and Last Name");
        return 0;
    }
    else {
        console.log("Thank You phone entered");
        return 1;
    }

};

function checkForm() {
    var validCount = 0;
    fieldCount = document.forms[0].elements.length - 1; //substract one for the submitbutton!
    var phoneNum = document.getElementById('phone').value;
    var name = document.getElementById('name').value;
    var myButton = document.getElementById('myButton');

    validCount += checkPhoneNumber(phoneNum);
    validCount += checkName(name);
    console.log(validCount + ' of ' + fieldCount + ' fields are valid');
    if (validCount > 0 && validCount === fieldCount) {//Compare the inputs to the number of valid inputs 
        myButton.disabled = false;
    }
    else {
        myButton.disabled = true;
    }
}

HTML

<form>
    First Name: <input type="text" id="name" /><label id="nameErrorPrompt"></label>
    <br />
    Phone Number: <input type="text" id="phone" /><label></label>
    <br />

    <button id="myButton" disabled="disabled">Test Me</button>
</form>
0

How about you start by making the onblur for each input return a boolean indicating if the field is valid.

Then setting a cansubmit variable (= checkName && checkPhone) in the checkForm function and only moving on after that - then you don't need to enable and disable the button.

If you really want the button to enable you can use the same pattern, but do

document.getElementById("myButton").disabled = !canSubmit;

and you will always want to call checkForm on field blur like you are now.

Also note you aren't scoping canSubmit locally right now.

Not the answer you're looking for? Browse other questions tagged or ask your own question.