Click here to Skip to main content
15,896,475 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I have a Dropdown and a Textbox. When the user selectes Phone, Fax, SMS from drop down , the textbox should be in auto phone format.

i.e the user can enter only number and the phone format should be like (999) 99 - 9999. This validation depends on the dropdown value.





Presently I am using the following javascript funtion for individual textboxes

JavaScript
function FormatedPhone(e) {
                
                    evt = e || window.event;
                    var keyPressed = evt.which || evt.keyCode;
                    
                    if (((keyPressed >= 97) && (keyPressed <= 122)) || ((keyPressed >= 65) && (keyPressed <= 90)) || (keyPressed == 59)) {
                        return false;
                    }
                    else {
                        if (keyPressed == 8 || keyPressed == 37) {
                            return;
                        }

                        var target = evt.target || evt.srcElement;

                        phone = target.value;
                        if (phone.length == 1 && phone != "(") {
                            target.value = "(" + phone;
                        }
                        else if (phone.length == 4 && phone.substring(0, 1) == "(" && !isNaN(phone.substring(1, 4))) {
                            target.value = phone + ") ";
                        }
                        else if (phone.length == 9 && phone.substring(0, 1) == "(" && !isNaN(phone.substring(1, 4)) && phone.substring(4, 5) == ")" && !isNaN(phone.substring(6, 9))) {
                            target.value = phone + "-";
                        }
                    }
                }


and I am calling this javascript funtion in .cs Page load by adding the attributes

C#
txtPhone1.Attributes.Add("Onkeypress", "return FormatedPhone(event)");



Please any body help me to format the javascript funtion according to my requirement ( accroding to dropdown value)



Thanks,

Nag
Posted

1 solution

What you are looking for is a masked input.
This[^] javascript library has helped me in the past and seems reasonably solid for that purpose.

If you have multiple different formats specified by a dropdown that then need to be applied to a text input, then you'll just have to change the mask on the fly and re-validate the textual content.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900