使用test()使用regexp进行信用卡验证 [英] Credit card validation with regexp using test()

查看:111
本文介绍了使用test()使用regexp进行信用卡验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试完成一些功课,看来这本书可能会弄错。我有一个简单的html页面,允许用户在我们的案例美国快递中选择一张信用卡。然后,用户输入一个数字,并根据正则表达式评估该数字。我的问题最终是当test()评估它返回布尔值或字符串的数字时?我应该比较那个字符串或布尔值? True == true应该在嵌套的if语句中触发代码。下面是本书给我的有效代码:

I'm trying to complete some homework and it appears the book might have gotten it wrong. I have a simple html page that allows user to pick a credit card in our case american express. The user then enters a number and evalutes that number based on a regular expression. My question ends up being when test() evaluates the number it returns a boolean or a string? I should then compare that string or boolean? True == true should fire off the code in a nested if statement. Heres what the book gives me as valid code:

if(document.forms[0].cardName.value == "American Express")
{
    var cardProtocol = new RegExp("^3[47][0-9]{13}$"); //REGEX ENTRY HERE
    if(cardProtocol.test(document.forms[0].cardNumber.value))     
        document.forms[0].ccResult.value = "Valid credit card number";
}

以上代码在firefox中不起作用。我尝试用2个警告来修改它,以确保数字是好的,布尔值很好......但仍然没有运气:

The above code doesn't work in firefox. I've tried modifying it with 2 alerts to make sure the number is good and the boolean is good...and still no luck:

if(document.forms[0].cardName.value == "American Express")
{
    var cardProtocol = new RegExp("^3[47][0-9]{13}$"); //REGEX ENTRY HERE <------
    alert(document.forms[0].cardNumber.value)
    alert(cardProtocol.test(document.forms[0].cardNumber.value))
    if((cardProtocol.test(document.forms[0].cardNumber.value)) == true ) // <--Problem
    {
        document.forms[0].ccResult.value = "Valid credit card number";
    }
    else
    {
        document.forms[0].ccResult.value = "Invalid credit card number";
    }
}

任何想法? if循环是罪魁祸首,但我不知道为什么它不起作用。请抛出if循环的代码!谢谢您的帮助!

Any ideas? the if loop is the culprit but I'm not figuring out why it is not working. Please throw up the code for the if loop! Thanks for the help!

推荐答案

此代码有效。请参阅 - http://jsbin.com/aqowa3

This code works. see - http://jsbin.com/aqowa3

要查看代码+ html,请参阅 - http://jsbin.com/aqowa3/edit

To view the code + html, see - http://jsbin.com/aqowa3/edit

确保你的html与你的js一致,并确保你在dom准备就绪后调用你的函数。

Make sure your html is consistent with your js and make sure you are calling your function after the dom is ready.

if(document.forms[0].cardName.value == "American Express")
{
    var cardProtocol = new RegExp("^3[47][0-9]{13}$"); //REGEX ENTRY HERE <------
    if(cardProtocol.test(document.forms[0].cardNumber.value)) {
       document.forms[0].ccResult.value = "Valid credit card number";
    } else{
       document.forms[0].ccResult.value = "Invalid credit card number";
    }
} 

这篇关于使用test()使用regexp进行信用卡验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆