Reputation: 10463
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
Upvotes: 0
Views: 151
Reputation: 9178
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>";
}
Upvotes: 0
Reputation: 49228
<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.
Upvotes: 1
Reputation: 6117
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
Upvotes: 1