Validating Phone Number based on country code - javascript

How to validate phone numbers based on country codes in Javascript.
For Example: India-starts with 91-xxxxxxxxxx, UK-44-xxxxxxxxxx, SZ-268-22xxxxxx and so on. Like this it should validate other countries country code with phone number which I will enter.
Below is the code which I tried but it is only for one country. Parallelly how to do validate with other countries country code.
function validateMobNo(mobno){
var mobno2;
var flag=false;
var mlen= mobno.length;
//alert(mobno.substr(3,mobno.length-3));
if(mobno.charAt(0)!='+' && mlen==10){
mobno2="+91-"+mobno;
alert("1>>your mobile wants to be in "+mobno2);
flag=true;
}
else if(mobno.charAt(0)=='+'){
if(mobno.substr(0,3)=='+91' && mobno.length==13){
mobno2=mobno.substr(0,3)+"-"+mobno.substr(3,mobno.length-3);
alert("2>>your mobile wants to be in "+mobno2);
flag=true;
}
}
else if(mobno.indexOf("-")<0&&mobno.length==12 && mobno.substr(0,2)=='91'){
mobno2=mobno.substr(0,2)+"-"+mobno.substr(3,mobno.length-2);
alert("3>>your mobile wants to be in "+mobno2);
flag=true;
}
else
alert("Please correct your mobile No");
if(flag==true)
document.mobvalidate.mobno.value=mobno2;
else
document.mobvalidate.mobno.focus()
return flag;
}

Using some method to loop over each country code and evaluates with regular erxpressions:
country_codes=['91-', 'UK-44-', 'SZ-268-22']
phone="91-123456789";
is_valid_number = country_codes.some(elem => phone.match('^' + elem));
console.log(is_valid_number );

Related

Form validation by country value

I have a query form with a country list. Mobile number and e-mail validation are working fine when the country India is selected, but when the user selects another country, I need mobile number validation off. Here is the code for validation:
<script type="text/javascript">
$(document).ready(function() {
$("#submitfeedback").click(function() {
var email = $("#fdbk_email").val();
var enqMobileNo= $("#fdbk_num").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (email == '' || enqMobileNo == '')
{
$("#returnmessage").append("<span>Enter your vaild E-mail & Mobile No.<span>");
return false;
}
var mailPattern = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!mailPattern.test(email))
{
$("#returnmessage").append("<span>Enter your valid email address!<span>");
return false;
}
var phoneNumberPattern = /^[0-9]{10}$/;
if(!phoneNumberPattern.test(enqMobileNo))
{
$("#returnmessage").append("<span>Enter your 10 digits mobile no only.<span>");
return false;
}
});
});
</script>
If I understand correct that you don't want to check mobile no when country is not India then I assumed your country is a dropdown field with id "country" then you can do following:
if($('#country option:selected').val() == 'india')
{
var phoneNumberPattern = /^[0-9]{10}$/;
if(!phoneNumberPattern.test(enqMobileNo))
{
$("#returnmessage").append("<span>Enter your 10 digits mobile no only.<span>");
return false;
}
}
Please update id selector and value accordingly

Javascript else if statement not working with form validation

I'm trying to validate a form that will send an email. At the moment the button returns formCheck() onclick. Which is meant to display a popup respective of field completetion.
I'm new to JS so I'm having a little trouble working out what I'm doing wrong as the outcome is always the else "Thanks".
<script>
function formCheck() {
if (document.getElementById("Name") === "")
{
alert("please enter name");
}
else if (document.getElementById("Email") === "")
{
alert("Please enter an email address");
}
else if (document.getElementById("Name") && document.getElementById("Email") === "")
{
alert("Please enter a Name and Email address");
}
else {
alert("Thanks");
}
}
</script>
To me it looks like I'm either not using an if statementcorrectly or its not picking up the fields are empty when defined as "". If anybody can point me in the right direction it would be much appreciated.
You should be comparing the value instead of the object itself:
document.getElementById("Name").value

Form input value validation

I have a question about contact form. I am not good in javascript. Here we go to the question.
I have a contact form on my website and one of the field called security that is for anti-spammers purpose. Currently, all the fields(except security) will be validated by javascript where i got from somewhere else. And, the field of security, will be validated by php code when submit. The security field is a math question. If you have complete all other fields, but provided a wrong answer to the security field, you will be redirected to the form and be required to do it all over again. I don't want the form to be this way.
Here to test the form --> http://www.jornes.com
What i want is, if the answer to the math question is 50, visitors can only pass the validation and submit the form with a correct answer. I want this value to be validated by javascript.
I'm looking for a solution to make the contact form even better. Any solutions?
Below is the javascript to process my existing form.
function validateForm(){
// set some vars
var name = document.getElementById('name');
var phone = document.getElementById('phone');
var email = document.getElementById('email');
var location = document.getElementById('location');
var findus = document.getElementById('findus');
var inquiry = document.getElementById('inquiry');
var msg = '';
if(name.value.length == ''){
msg+= '*How shall i address you? \n';
name.className = 'inpBoxError';
}
else if(name.value.length < 3){
msg+= '-Your name is too short, my friend! \n';
name.className = 'inpBoxError';
}
else if((name.value.length<3)||(/[^a-z\s\'\-\.]/gi.test(name.value))) { // invalid - must be minimum of 5 character only
msg+= '-Please enter your name with words only! \n';
name.className = 'inpBoxError';
}
else if ((phone.value.length == '')) {
msg+= '*You should have a cell phone, i guess?! \n';
phone.className = 'inpBoxError';
}
else if ((phone.value.length<1)||(/[^0-9]/gi.test(phone.value))) { // invalid - must be minimum of 10 digits only
msg+= '-Only Numeric for Phone Field!(Ex:0123456789) \n';
phone.className = 'inpBoxError';
}
else if ((phone.value.length<10)||(/[^0-9]/gi.test(phone.value))) { // invalid - must be minimum of 10 digits only
msg+= '-Please enter a valid phone number! "10 digits" \n';
phone.className = 'inpBoxError';
}
else if ((email.value.length == '')) {
msg+= '*Email is also a good way for us to communicate. \n';
email.className = 'inpBoxError';
}
else if(!/^([a-z0-9])([\w\.\-\+])+([a-z0-9]?)\#((\w)([\w\-]?)+\.)+([a-z]{2,4})$/i.test(email.value)) { // invalid
msg+= '-Invalid email format! \n';
email.className = 'inpBoxError';
}
else if(location.value.length == ''){
msg+= '*Please tell me where are you from! \n';
location.className = 'inpBoxError';
}
else if(location.value.length < 5){
msg+= '-Location name is too short! I am not sure where is the place. \n';
location.className = 'inpBoxError';
}
else if(purpose.value == ''){
msg+= '*You contact me for...? \n';
purpose.className = 'multipleError';
}
else if(findus.value == ''){
msg+= '*How did you find me? Did i know you? \n';
findus.className = 'inpSelectError';
}
else if(inquiry.value.length == ''){
msg+= '*At least tell me something! \n';
inquiry.className = 'messageBoxError';
}
else if(inquiry.value.length < 50){
msg+= '-Your message is too short! "Minimum 50 characters." \n';
inquiry.className = 'messageBoxError';
}
else if(security.value == ''){
msg+= '*You must provide correct answer to submit this form! \n';
security.className = 'inpBoxError';
}
// SUbmit form part
if(msg == ''){
return true;
}else{
alert(msg);
return false;
}
}
Even the dumbest bot can parse Security: 7+3 perhaps you want to use words or images.
You can use a regex to validate the security form field but even this one could be analysed by spam bots. I would not validate this field in the frontend. The server should test it an in case of an error return the form again with prefilled with the former user input.
If you want you can add a hidden field, that should not filled at all. If your id or label of this hidden field is clever chosen many spam bots will fill something in, and you can use this information to block them.

validating using input.value.match in javascript

I believe I have a fairly simple problem, but I am unfortunately unable to resolve it. I have searched for a while and tried several different variations of this code but cannot seem to get it to work.
All I am trying to do is check and see if my input value has a alpha character in it opposed to a number.
Here is my js function:
function checkLetters(input) {
var numOnly = /^[0-9]+$/;
var hasLetters = false;
if (!input.value.match(numOnly)) {
hasLetters = true;
}
return hasLetters;
}
and here is the code calling it:
<input type="text" name="cc_number" size="13" maxlength="11" onblur="
if(checkLength(cc_number.value) == true) {
alert('Sorry, that is not a valid number - Credit Card numbers must be nine digits!');
} else if (checkLetters(cc_number.value) == true) {
alert('Credit Card number must be numbers only, please re-enter the CC number using numbers only.');
}">
Any help or suggestions would be appreciated.
It looks like you're trying to validate credit card input. May I suggest a different approach?
function checkCardInput(input,errorId) {
var errorNoticeArea = document.getElementById(errorId);
errorNoticeArea.innerHTML = '';
if(!input.value) {
errorNoticeArea.innerHTML = 'This field cannot be left blank.';
return;
}
if(!input.value.match(/[0-9]/)) {
errorNoticeArea.innerHTML = 'You may only enter numbers in this field.';
input.value = '';
return;
}
if(input.value.length != 9) {
errorNoticeArea.innerHTML = 'Credit card numbers must be exactly 9 digits long.';
return;
}
}
See this jsFiddle for an example use.
You're passing cc_number.value as input, but then referencing input.value.match(), which works out to:
cc_number.value.value.match();
Just pass cc_number:
if (checkLetters(cc_number)) {
...
}

Multiple form onsubmit validations?

I have a form and currently I have a javascript code to validate my form to make sure that the user fills out every input. my form action includes:
onsubmit="return validateForm();"
Which is the javascript to make sure every field is filled out. If it makes any difference, here is my javascript code:
<script type="text/javascript">//
<![CDATA[function validateForm() {
var a=document.forms["myform"]["inf_field_FirstName"].value;
var b=document.forms["myform"]["inf_field_Email"].value;
var c=document.forms["myform"]["inf_field_Phone1"].value;
if (a==null || a=="" || a=="First Name Here")
{ alert("Please enter your First Name!");
return false; }
if (c==null || c==''|| c=="Enter Your Phone Here")
{ alert("Please insert your phone number!");
return false; }
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.myform.inf_field_Email.value.search(emailRegEx) == -1)
{ alert("Please enter a valid email address.");
return false; } }
// ]]>
</script>
However on the phone number field, defined at c, I want to add another script that will pop up if the user doesn't enter a phone number at least 9 digits long. I was thinking of adding a code like this
<script type="text/javascript">
function validate(){
var c=document.forms["myform"]
if (input.length<9){
alert("Please enter a real phone number")
return false
}else {
return true
}
}
</script>
However I don't know how to run both functions on submit. I am extremely new to javascript so excuse me if there's already a simple solution to this.
Thanks
Everything in quotes after onsubmit= is just javascript. You can make sure both functions return true by doing:
onsubmit="return validateForm() && validate();"
You could add it as another rule in that conditional. For example:
if (c==null || c==''|| c=="Enter Your Phone Here" || c.length < 9) {
alert("Please insert your phone number!");
return false;
}
It's probably best to refactor this code, but that's probably the fastest way to do what you need.

Categories