0

I have a Javascript code (below) which validates mobile numbers. It's working fine. But the problem I am facing is both valid and invalid mobile numbers are being inserted into the database. I want only valid mobile numbers to be inserted into the database.

The code is as follows. Can anyone suggest any ideas to change the code?

<script type="text/javascript">
  function CheckINumber(INumber) {
    var INum = /^[+]{1}[0-9]{2}-\d{10}$/;
    if(INum.test(INumber)) {
      alert("Your Mobile Number Is Valid.");
    } else {
      alert("Your Mobile Number Is Not Valid.");
    }
  }
  <input name="Upload" type="submit" height="25" class="uploadbutton" onClick="CheckINumber(mobile.value);"
4
  • return False after "Invalid alert". i.e. before closing brace of else in this case. Commented Jan 5, 2013 at 5:36
  • otherwise, by default it executes further code, considering that every entered number is valid. Commented Jan 5, 2013 at 5:43
  • 1
    You need to validate in the server-side too, because the user can disable javascript and bypass your client-side validation. Commented Jan 5, 2013 at 6:01
  • Hi sujith thanks for your suggestion I tried but then also it is being inserted into database... Commented Jan 5, 2013 at 8:15

2 Answers 2

2

Are you using a form? If so you should do:

<form method="post" name="form_name" action="your_submit_url" onsubmit="return(CheckINumber(mobile.value));">

Also:

function CheckINumber(INumber)
{
  var INum = /^[+]{1}[0-9]{2}-\d{10}$/; 

  if(INum.test(INumber)) { return true; }
  return false;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Insert false in the invalid case to signal it failed to prevent the script from continuing.

if(INum.test(INumber))
{
 alert("Your Mobile Number Is Valid.");  
} 
else
{
  alert("Your Mobile Number Is Not Valid.");  
  return false;
}

1 Comment

+1 for correct answer. But an explanation to go with the answer will make it useful to everyone viewing the post and not just the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.