0

I'm trying to do code that errors out a form validate if the form contains "VP-".

My code is:

// quick order form validation
function validateQuickOrder(form) {        
  if ((form.ProductNumber.value == "")|| (form.ProductNumber.value == "VP")){
        alert("Please enter an item number.");
        form.ProductNumber.focus();
        return false;
 }
        return true;
}
James Anderson
  • 815
  • 1
  • 13
  • 23

2 Answers2

1

== does a full string comparison. You'll want to use indexOf to check if it contains that string:

if ( ~form.ProductNumber.value.indexOf('VP') ) {
    // ProductNumber.value has "VP" somewhere in the string
}

The tilde is a neat trick, but you can be more verbose if you want:

if ( form.ProductNumber.value.indexOf('VP') != -1 ) {
    // ProductNumber.value has "VP" somewhere in the string
}
Community
  • 1
  • 1
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

Just to provide an alternative to the other answer, regex can be used as well:

if ( /VP/.test( form.ProductNumber.value ) ) {
  // value contains "VP"
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171