编辑:我无法使用正则表达式,因为这是针对一堂课的,而我的教授希望我们学习字符串操作的价值!
我需要使用字符串操作来验证表单中的电话号码。我需要使用的逻辑(对于班级要求)是将电话号码与2个字符串进行比较,然后输出一个新字符串。然后将新字符串与4种掩码电话号码类型进行比较,以验证其为true。
由于某种原因,它仅打印“ dddddddddd”。我使用了错误的循环类型吗?我关闭得太早了吗?请看下面:
Javascript:
<script type="text/javascript" language="JavaScript">
function validatePhone()
{
// kb- this is the phone number the end user will input into the form
phoneString = document.PizzaForm.phone.value;
// this is a number string I will use to compare the phone number against to confirm if it is a number
var numberString = "1234567890";
// kb- this is an operator string I will use to compare the phone number against to confirm if it has symbols in it such as (,), or -
var operatorString= "()-";
//kb- this is a dummy string I will be creating through this function
var dummyString= "";
// kb- these are the 4 mask ID phone numbers. If the phone number does not fit one of these masks, it will not be a valid phone number
var mask1= "dddddddddd";
var mask2= "(ddd)ddddddd";
var mask3= "(ddd)ddd-dddd";
var mask4= "ddd-ddd-dddd";
console.log(phoneString);
// kb- this is my for loop to go through the entire phone number string character by character
for (var i=0; i <phoneString.length; i++)
{
var c = phoneString.charAt(i);
//kb- if the character in the phone string is true (a #), please add a D to the dummy string
if (numberString.indexOf(phoneString) != -1)
{
dummyString +="d";
}
// kb- if the character is not a number, if it is a '(', please add that to the dummy string
else if (operatorString.indexOf(phoneString) ==0)
{
dummyString +="(";
}
//kb- if the character is not a number or a '(', if it is a ')',please add that to the dummy string
else if (operatorString.indexOf(phoneString) ==1)
{
dummyString +=")";
}
//kb- if the character is not a number, a '(' or ')', but it is a '-', please add that to the dummy string
else if (operatorString.indexOf(phoneString) ==2)
{
dummyString += "-";
}
}
// kb- please print this to the console
console.log("dummyString is" + dummyString);
// if the final dummy string matches 1 of the 4 mask IDs, alert as a true phone number
if (dummyString == mask1 || dummyString== mask2 || dummyString ==mask3 || dummyString == mask4)
{
alert (dummyString);
}
return;
}
HTML:
form name= "PizzaForm">
<input type= "text" name="phone">
<input type = "button" value = "Submit Order" onClick = "validatePhone()"/>
</form>
答案 0 :(得分:1)
我只看代码而不运行它的印象是,您应该在第一笔phoneString
中将if
替换为c
(例如:if (numberString.indexOf(c) != -1)
... )。毕竟,它是您要测试的c
中的每个字符(又名phoneString
),而不是整个phoneString
,对吗?