NewCodeMan NewCodeMan - 1 month ago 7
Javascript Question

How to validate data format, data & focus form fields through function

Need help getting this

function
to:

Validate data format

Validate data is existing

Focus on missing fields (One at a time is fine)

The function below is updated from some advice. It works much better then my original. Problem though is if email
field
is blank it works great, wont move on until value is put in. But the other fields will focus correctly, but still allow the func to move to
else
, which just lowers opacity as you can see.

function quantity_box() {

// store all your field names in an array
var fieldNames = ["EMAIL", "BILLTOFIRSTNAME", "BILLTOLASTNAME"];

// loop over each field name in that array
for (var i = 0; i < fieldNames.length; i++) {

// extract the field name
var fieldName = fieldNames[i];

// use the field name to index the form object and get the field itself
var field = document.forms["billing_form_id"][fieldName];

// check the field's value to see if it's empty
if (field.value === '') {
field.focus();

// break from our loop, since we've already found an invalid value
break;

}else{

$(".prod_billing_box").delay(0).animate({"opacity": "0"}, 200);
$(".prod_quantity_box").delay(215).animate({"opacity": "1"}, 200);

}
}


Also a note. Even though fields like EMAIL have settings like TextMode="Email" to verify proper format, the above function also ignores that.

Answer Source

You've misunderstood how indexes work. The following line is valid, but not doing what you expect it to.

["EMAIL" && "BILLTOFIRSTNAME" && "BILLTOLASTNAME"]

What this is actually doing is performing a boolean expression using and operations, like you would in an if statement. If you actually run that line in your javascript console, it will print out

"BILLTOLASTNAME"

Which is still valid, but not what you want.

Instead, you need to loop over all the form fields and check each one to make sure it's valid. If any of the fields are invalid, you can break out of the loop.

// track if the entire form is valid, start true
var allValid = true;

// store all your field names in an array
var fieldNames = ["EMAIL", "BILLTOFIRSTNAME", "BILLTOLASTNAME"];

// loop over each field name in that array
for (var i = 0; i < fieldNames.length; i++) {
  // extract the field name
  var fieldName = fieldNames[i];
  // use the field name to index the form object and get the field itself
  var field = document.forms["billing_form_id"][fieldName];
  // check the field's value to see if it's empty
  if (field.value === '') {
    field.focus();
    // our entire form isn't valid
    allValid = false;
    // break from our loop, since we've already found an invalid value
    break;
  }
}