Viewing 1 replies (of 1 total)
  • Plugin Author Jason Lau

    (@jason-lau)

    The telephone field is an HTML5 field and may not yet be fully supported by all browsers. However, I recommend keeping it, as opposed to changing to any other type of field, because it WILL be supported in the near future.

    Consider this – not all phone numbers are ###-###-#### format.
    754-3010
    Local
    (541) 754-3010
    Domestic
    +1-541-754-3010
    International
    1-541-754-3010
    Dialed in the US
    001-541-754-3010
    Dialed from Germany
    191 541 754 3010
    Dialed from France

    If you absolutely need ###-###-#### format, it can be achieved using JavaScript.

    Below is a complete example I made for you. In the example, I use JavaScript to validate the field after it has been changed.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
    	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    	<meta name="author" content="JasonLau.biz" />
    
    	<title>Validate Phone Number - JasonLau.biz</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <style type="text/css">
    <!--
    	.field-error{
    	   background-color: #FFFF99;
           border: 1px solid red;
    	}
    
        .tele-error-message{
            color: red;
        }
    -->
    </style>
    <script type="text/javascript">
    jQuery(function($){
       var is_valid_phone_number = function(phone_number){
        var regExpObj = /\d\d\d-\d\d\d-\d\d\d\d/;
        if(regExpObj.exec(phone_number) == null || phone_number.length != 12){
            return false;
        } else {
            return true;
        }
       }
       $('.my-phone-field-class').change(function(){
        if(!is_valid_phone_number($(this).val())){
            $(this).toggleClass('field-error', true);
            if(!$('span.tele-error-message').html()){
               $(this).after(' <span class="tele-error-message">Invalid phone number format. Please use ###-###-#### format.</span>');
            }
        } else {
            $(this).toggleClass('field-error', false);
            $('span.tele-error-message').fadeOut().remove();
        }
       });
    });
    </script>    
    
    </head>
    
    <body>
    
    <input type="tel" class="my-phone-field-class" name="phone" />
    
    </body>
    </html>

Viewing 1 replies (of 1 total)
  • The topic ‘How to validate phone numbers?’ is closed to new replies.