How can I mask an HTML input using javascript? -
how can mask phone using javascript on html control.
i input force text in following format:
[(111)111-1111]
here have currently:
mask(str, textbox, loc, delim) { var locs = loc.split(','); (var = 0; <= locs.length; i++) { (var k = 0; k <= str.length; k++) { if (k == locs[i]) { if (str.substring(k, k + 1) != delim) { str = str.substring(0,k) + delim + str.substring(k,str.length) } } } } textbox.value = str }
there 3 common ways handling phone number input of guaranteed format:
1. accept numerical input anyway
the likelihood of users obscure numbers still living in higher ever. accepting kinds of numerical input alleviates concern number useless if gave either not enough numbers or wrong ones.
2. split 3 text boxes of fixed lengths
a lot of financial software this. not sure why, specifically, seems rather frequent there. recommendation advance cursor after keypress next box if they've typed max limit on textboxes. also, guarantees numbers in whatever format you're expecting, because can append resulting post variables together.
example of html:
<input id="phonepart1" maxlength="3" name="phonepart1"/> <input id="phonepart2" maxlength="3" name="phonepart2"/> <input id="phonepart3" maxlength="4" name="phonepart3"/>
and little jquery snippet merge 3 in format:
var phonepart1 = parseint($("#phonepart1").val(), 10); var phonepart2 = parseint($("#phonepart2").val(), 10); var phonepart3 = parseint($("#phonepart3").val(), 10); var phone = "("; if (isnan(phonepart1)||isnan(phonepart2)||isnan(phonepart3)) { // incorrect format } else { phone = phone + phonepart1 + ")" + phonepart2 + "-" + phonepart3; }
3. use regular expression match number format
you can use combination of regular expressions match multiple numbers, or explicitly 1 asking about. technique you're looking for. regular expression:
/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/
you'd use this:
if (yourphonevariable.match(/\([0-9]{3}\)[0-9]{3}-[0-9]{4}/)) { // it's valid }
4. if you're looking format text mask...
consider jquery plugin @ http://digitalbush.com/projects/masked-input-plugin/. user @john gietzen suggested me outside of post, feel free give him kudos it.
Comments
Post a Comment