javascript - Input alters text box format -
i new javascript , have been doing work creating form in html , javascript. in work have been trying validate format of input depending on text entered previous field.
what have been trying if country 'australia' entered 'country' text box 'telephone' text box limited format (00)00000000 , if other country 'telephone' text box must formatted in international number way including + , country code following e.g. +61 etc
i have done of function far:
<script> document.getelementbyid('txttelephone').onchange = function() { var num1 = document.getelementbyid('txttelephone').value, country = document.getelementbyid('txtcountry').value, regex; if (country == "australia" || country == "australia") { regex = /\(\d{2}\)\d{8}/; } else { regex = /\+\d{15}/; } if (!num1.match(regex)) { alert('that not correct telephone number'); } } </script>
that function did limit string length of 'telephone' text box 12 characters still have yet validate make sure area code included in between brackets in the form of (00)00000000 , validate + included if country other australia (international numbers including country codes).
here html have use function on:
<b>country:</b> <input type="text" id="txtcountry" name="country"> <br> <b>telephone:</b> <input type="text" id="txttelephone" name="telephone">
any appreciated!
what need regular expression test whether telephone number matches format want.
here 1 australian numbers /\(\d{2}\)\d{8}/
. regex starts , ends /
match opening bracket \(
followed 2 digits \d{2}
closing bracket \)
, 8 nore digits \d{8}
.
so function become
//changed onchange event of `txttelephone` document.getelementbyid('txttelephone').onchange = function(){ var num1 = document.getelementbyid('txttelephone').value, //added .value here country = document.getelementbyid('txtcountry').value, regex; if(country == "australia" || country == "australia"){ regex = /\(\d{2}\)\d{8}/; } else { regex = /\+\d{15}/; } if(!num1.match(regex)){ //if there not match number format alert("thats not ruddy telephone number!"); } }
as side note, urge not let users "free" type country in typos means logic not work i.e need user enter australia or australia , nothing else do, dropdowns invented scenario :).
Comments
Post a Comment