[SalesForce] Custom Validation on Input field phone

<div class="col-md-6" style="margin-bottom:1%;">
<apex:input type="tel"  value="{!telephone}" html-pattern="[0-9]" html-placeholder="Telephone" html-oninvalid="setCustomValidity('Please Enter only numbers')" html-oninput="setCustomValidity(' ')" />
</div> 

I have this code in my vf page. I want to put a custom validation on this field instead of default validation message. It is showing me my required custom validation when input doesn't match but I am unable to submit when I put exact match it is still showing the message.

Best Answer

It is possible to validate phone number using <apex:input> also, Just give an id to your element and retrive its value in a javascript function.

You can use a javascript function for validating as shown below : Here "num" is the value to validate.

  function validatePhone(num)
    {
        var mobPattern = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/;
        //pattern matcher for salesforce phone field

        if(!num.match(mobPattern))
        {
            //do something for valid number.
        }
        else
        {
            //do something for invalid number.
             alert('Invalid number');
        }
    }

The mobPattern will match with the standard salesforce field.

First try the pattern using online Regex validator : online Regex validator