简体   繁体   English

验证表单JavaScript

[英]validate form JavaScript

I'm trying to validate some of the field in my form. 我正在尝试验证表单中的某些字段。

and I want to check if they have input the correct area code of the required field. 我想检查他们是否输入了所需字段的正确区号。

The area code should be one of 212 , 313 , or 414 区号应的一个212313 ,或414

This is homework so I can't use regular expression, and I'm not really asking for an answer but here is what I'm trying to use but non of them really worked for me 这是家庭作业,所以我不能使用正则表达式,我不是真的要求答案,但这是我正在尝试使用但不是他们真的为我工作

if (input.substr(0,2) != 212|| input.substr(0,2) != 313 || input.substr(0,2) != 414)
                Message += " <p>Sorry but you have enter wrong area code!!!</p>";

I've tried used substring indexOf but really I don't know non of them really correct in this case. 我已经尝试过使用substring indexOf但实际上我并不知道在这种情况下它们是非常正确的。

Is there anyway to validate but not with the regular expression? 无论如何要验证,但不是正则表达式?

Thanks 谢谢

Try this 尝试这个

if (input.substr(0,3) != 212|| input.substr(0,3) != 313 || input.substr(0,3) != 414)
      Message += " <p>Sorry but you have enter wrong area code!!!</p>";

I didn't test it though 我没有测试它

<input type="text" id="num"/>
<div id="msg"></div>

// This should run in a window.onload or $(document).ready() block
var num = document.getElementById('num'),
    msg = document.getElementById('msg');

num.onblur = function(){
    var areacodes = '212|313|414|',
        areacode = this.value.replace(/[^0-9]/, '').substring(0,3),
        message = 'Area code validates.';

    if (areacode.length < 3 || areacodes.indexOf(areacode + '|') === -1) {
        message = "Sorry but you have entered an invalid area code.";
    }

    msg.innerHTML = message;
};

http://jsfiddle.net/userdude/gfJWX/1 http://jsfiddle.net/userdude/gfJWX/1

input I'm guessing is a string variable, and not a DOM note pointing to an input element. input我猜是一个string变量,而不是指向input元素的DOM注释。

Shouldn't this work? 这不应该工作吗?

var str = input.trim().substr(0,3);
if ( !{212:1, 313:1, 414:1}[ str ] ){
    Message += " <p>Sorry but you have enter wrong area code!!!</p>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM