Form Validation: If data in form contains “VP-”, e

2019-09-11 04:24发布

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

2条回答
祖国的老花朵
2楼-- · 2019-09-11 04:38

== 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
}
查看更多
狗以群分
3楼-- · 2019-09-11 04:40

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

if ( /VP/.test( form.ProductNumber.value ) ) {
  // value contains "VP"
}
查看更多
登录 后发表回答