Skip to content Skip to sidebar Skip to footer

Form Validation: If Data In Form Contains "VP-", Error Out

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

Solution 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
}

Solution 2:

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

if ( /VP/.test( form.ProductNumber.value ) ) {
  // value contains "VP"
}

Post a Comment for "Form Validation: If Data In Form Contains "VP-", Error Out"