简体   繁体   中英

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

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.

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

input I'm guessing is a string variable, and not a DOM note pointing to an input element.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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