Click here to Skip to main content
15,885,032 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
JavaScript
function validate(){
    var isValid = true;
    var regPhone = /^\+?([0-9]{2})\)?[-. ]?([0-9]{5})[-. ]?([0-9]{5})$/;
    var phone = document.getElementById('phone').value.trim();
    if (!regPhone.test(phone)) {
        document.getElementById('phoneErr').innerHTML = 'Please enter minimum 10 numbers';
        document.getElementById('phone').focus();
        isValid = false;
    } else {
        document.getElementById('phoneErr').innerHTML = '';
    }
}


What I have tried:

HTML
<form name="contactForm" onsubmit="validate(event)" action="#" method="post">
  <div class="row">
        <label>Phone</label>
        <input type="text" id="phone" maxlength="20">
        <div class="error" id="phoneErr"></div>
    </div>
    <div class="row">
        <input type="submit" value="Submit">
    </div>
</form>
Posted
Updated 17-Jan-22 20:22pm
v4

1 solution

It will depend on your actual data: if it consists of a plus, followed by two digits, a hyphen, five digits, a hyphen, a final five digits and nothing else then it will match (the hyphens can be a space or period instead).
If it doesn't, it won't.

So start by find9ing out exactly what is in phone and work from there. We can't do that for you!
It may be worth your getting a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
 
Share this answer
 
Comments
Joshna J U 17-Jan-22 9:03am    
Bt if I give letters error is not showing
OriginalGriff 17-Jan-22 9:33am    
Because the test is only performed on Submit, not a button Click - which means it gets posted to the server which (almost certainly) reloads the page ...
Joshna J U 17-Jan-22 10:43am    
in the html part , there is a div to show the error message ,its is not working..
i tested same with email,password input fields error message is showing bt here its not working...
OriginalGriff 17-Jan-22 11:04am    
So compare exactly how they differ - I can't do that as I can't see the other ones, can I?
Joshna J U 17-Jan-22 11:07am    
Email Address



---------------
var regEmail = /^\S+@\S+$/;
var e_mail = document.getElementById('email').value.toLowerCase().trim();
if (!regEmail.test(e_mail)) {
document.getElementById('emailErr').innerHTML = 'Please enter a valid email address.';
document.getElementById('email').focus();
isValid = false;
} else {
document.getElementById('emailErr').innerHTML = '';
}

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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