【问题标题】:Form Validation: If data in form contains "VP-", error out表单验证:如果表单中的数据包含“VP-”,则报错
【发布时间】:2013-01-03 19:12:00
【问题描述】:

我正在尝试编写代码来验证表单是否包含“VP-”。

我的代码是:

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

【问题讨论】:

  • 什么不起作用?预期什么,你得到什么?
  • 如果它是或如果它包含?因为你只是在检查它是否是字面上的“VP”。
  • 期待收到警报,但没有收到任何信息;使用我上面的代码提交表单仍然没有问题。我希望它遇到问题,并在我输入包含“VP”的产品编号时显示警报
  • form.ProductNumber.value.indexOf('VP') > -1
  • @Aidanc - 如果它包含字符串中的任何位置。

标签: javascript forms validation


【解决方案1】:

== 进行完整的字符串比较。您需要使用indexOf 检查它是否包含该字符串:

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

波浪号是a neat trick,但如果需要,您可以更详细:

if ( form.ProductNumber.value.indexOf('VP') != -1 ) {
    // ProductNumber.value has "VP" somewhere in the string
}

【讨论】:

    【解决方案2】:

    只是为了提供另一个答案的替代方案,也可以使用正则表达式:

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

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 2022-01-14
      • 2019-04-13
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      相关资源
      最近更新 更多