I am trying to validate and return a textbox input field bu using
var ok = phNum.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (ok==0) {
var parts = phNum.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
output.value='('+parts[1]+') '+parts[2]+'-'+parts[3];
}
which is supposed to accept: 555-555-1234, 5555551234, (555) 555-1234, etc. and return: (555) 555-1234 at this demo .
Here is the code I have
<input id='phone'></input>
<script>
$("#phone").on("load change keyup paste", function (e) {
if (e.keyCode == 8) {} else {
var output;
var input = $("#phone").val();
$("#phone").val(output);
var ok = phNum.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (ok == 0) {
var parts = phNum.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
output.value = '(' + parts[1] + ') ' + parts[2] + '-' + parts[3];
}
}
});
</script>
but I am not getting the result back! Why is this happening and how I can fix this?
Instead of javascript, you could use the browsers built in regex pattern matcher:
<input id='phone' pattern="/^\(?\d{3}\D*\d{3}\D*\d{4}$/"></input>
and..... "output" is not defined:
var output;
Then you use it:
$("#phone").val(output); //What's the value of "output" here? : undefined
Plus.... if you check the input every time you change its value, you will be checking it also when you type the first number. That will not match your regex, so it removes it....
Edit:
Check this code: http://jsfiddle.net/hza0wex5/5/ It will only format the number if the input has at least 10 characters
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.