Javascript Input Numbers Only Regular Expressions - javascript

I have a RegEx validation that validates the field to be number only. However, what happens is the validation will only return true if the length of the string is more than 10 digits. But if less than 10, let's say 5, it returns false.
Here's my code:
function isNumeric(elem, helperMsg) {
var numericExpression = /^[0-9]+$/;
if (elem.value.match(numericExpression)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
}
function formValidator() {
var phone = document.getElementById('home');
if (isNumeric(phone, "Please enter a valid Australian House Phone Number")) {
console.log("Passed phone number");
if (isNumericPostal(postal, "Please enter a valid Postal Code of Australia it should be 4 digits only")) {
return true;
}
}
}
}

you are also mixing validation logic with UI logic in your isNumeric function. It's bad practice. /^\d{10,13}$/.test(yourValue) will return true/false - should be better in this case.
function isNumeric(val) {
return /^\d{10,13}$/.test(val);
}
function formValidator() {
var phone = document.getElementById('home');
if (!isNumeric(phone.value)) {
alert("Please enter a valid Australian House Phone Number");
phone.focus();
return false;
}
// do your other logic in similar manner
return true;
}

This is what you need:
/^[0-9]{0,13}$/
This will validate that the input string is between 0 to 13 digits length. So even if it 9, 10 digits it will pass.
If you have some minimum digit length as well, then change the {0,13} accordingly.
Between, http://www.regexr.com/ is a good site to create regex and test them.

Use this regex ^(\d){9,13}$ instead

Related

why it is not working to validate only numbers, not going to true condition

The following function is for validating numbers.
function strictlynumber(obj)
{
var numbers=/^[0-9]+$/;
if (obj!=numbers)
{
alert("please enter numbers only");
return false;
}
return true;
}
Use regexObject.test(obj) method,
In your code obj!=numbers , is a test of equality , it will always return true.
Modified code :
function strictlynumber(obj)
{
var numbers=/^[0-9]+$/;
if (!numbers.test(obj))
{
alert("please enter numbers only");
return false;
}
return true;
}
Please follow the below link for more info on Regular Expression :
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
You have to test the value against the Regex. You can not simply compare the value passed with Regex object in that way. Try the following:
function strictlynumber(obj) {
var numbers=/^[0-9]+$/;
if (!numbers.test(obj)) {
alert("please enter numbers only");
return false;
}
return true;
}
console.log(strictlynumber(5))
Your statement obj!=numbers is comparing the regular expression /^[0-9]+$/ to obj
You need to execute the regular expression against the input such as.
function strictlynumber(obj)
{
var numbers=/^[0-9]+$/;
if (!obj.match(numbers))
{
alert("please enter numbers only");
return false;
}
return true;
}
Here we use the match method of a string prototype.

Number validation in JavaScript

I have created an external JavaScript to validate a form I created in HTML. Some of the validation works, but when I use the same code to validate other fields it will not work. E.g. postcode must contain numbers - if not, postcode is invalid.
I tried using the same code for a credit card, i.e. credit card must have 16 digits - if not, the credit card number is invalid. I wrote the code for postcode and it worked, but when I tried to reaarrange it to suit the credit card function, it did not work. Not too sure why? Should I have used a different function?
Here is my external javascript:
function validateForm()
{
if (isNaN(document.getElementById("postcode").value))
{
alert ("Your postcode is not valid");
}
else
{
alert ("You have entered your postcode correctly");
}
if (document.getElementById ("email").value.length < 5 ||
document.getElementById ("email").value.indexOf("#")== -1)
{
alert("Please enter your email min 5 chars and include # symbol");
document.getElementById("email").focus();
return false;
}
if (isNaN(document.getElementById("creditcard").value))
{
alert ("Your creditcard is not valid");
}
else
{
alert ("You have entered your creditcard correctly");
}
alert("Thank you for your submission!");
return true;
}
So first off, you probably don't want to prompt the user with 10 error dialogs at a time.
So you should nest your if else clauses & the function will stop after the first error.
Second, isNaN is doubtfully a good evaluator because input.value may return a value of type string. Using a regex is a more robust way of error checking inputs. Third, you want to account for the user's confusion mistakes. Users often think (me too): 'wait, should I also write the dash on my credit card here?'.
So you'll remove dots, dashes & whitespace before proceeding (those could unknowingly be included). Other chars are just invalid. For your credit card input, that would be:
var ccVal = document.getElementById("creditcard").value;
// remove dots, dashes & whitespace
ccVal = ccVal.replace(/(\s|\.|\-)/g, '');
// if any other chars there, input value = incorrect & stop function
if ( ccVal.match(/\D/) ) {
alert('A credit card number only has decimals, silly.');
return false;
} else {
// Check for length now
if ( ccVal.length !== 16) {
alert('A credit card has 16 decimals, silly.');
return false;
} else {
// more checks
document.getElementById('myform').submit()
}
}
See an implementation example here: http://jsbin.com/betawahi/1/edit
isNaN checks if the value is not an integer, you'll need an additional check for the length.
Keeping the code similar to the way you've set out the rest of the function, to check if the credit card is a number and a length of 16, you'll want:
if( !(isNaN(document.getElementById("creditcard").value) && document.getElementById("creditcard").value.length === 16) {
alert("Credit Card Is Valid");
}else{
alert("Your Credit Card is Not Valid");
return false;
}

Javascript phone and number field wont validate correctly submits form anyway

Update:
the script below will throw an error if I enter in a 9 digit phone number, and accept a 10 digital one ...... but it will also accept just a single digit - how can I stop this from happening.
and for the collector field I need it to accept only 11 numbers.
I'm trying to amend my validation code to validate for phone numbers, it seems like an easy enough task but I can't get it to work correctly.
The script should check to see if it is 9 digits long, spaces, dashes or no spaces are okay. If no phone is entered it should give the required error. If the field has only 8 digits for example entered it should give the invalid phone error.
Please see the code at this jsfiddle - http://jsfiddle.net/5zFqS/7/
function validate_required(field,alerttxt) {
with (field) {
if (value==null||value=="") {
alert(alerttxt);return false;
} else {return true;}
}
}
function validate_email(field,alerttxt) {
with (field) {
apos=value.indexOf("#");
dotpos=value.lastIndexOf(".");
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false;}
else {return true;}
}
}
function validate_Phone(field,alerttxt) {
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(field.value.match(phoneno)) {
alert(alerttxt);return false;
} else {return true;}
}
function validate_collector(field,alerttxt) {
var collect = /^\d{12}$/;
if(field.value.match(collect)) {
alert(alerttxt);return false;
} else {return true;}
}
function validate_form(thisform) {
with (thisform) {
if (validate_required(firstName,"Please enter your First Name")==false)
{firstName.focus();return false;}
if (validate_required(lastName,"Please enter your Last Name")==false)
{lastName.focus();return false;}
if (validate_required(email,"Please enter your Email Address")==false)
{email.focus();return false;}
if (validate_email(email,"Please enter a valid Email Address")==false)
{email.focus();return false;}
if (validate_required(phone,"Please enter your Phone")==false)
{phone.focus();return false;}
if (validate_Phone(phone,"Please enter a valid Phone Number")==false)
{phone.focus();return false;}
if (validate_required(province,"Please select your Province")==false)
{province.focus();return false;}
if (validate_required(collector,"Please enter Collector Number")==false)
{collector.focus();return false;}
if (validate_collector(collector,"Please enter a valid Collector Number")==false)
{collector.focus();return false;}
}
}
I think I have a syntax error but I can't see it.
You need to remove the semi-colon at the end of this line:
if (field.match(/^\d{9}/));
You said that spaces etc., should be okay. In which case, you'll need to remove (or ignore) them:
var reg = /\D/g; // \D identifies non-digit characters, g means 'global'
var stripped = "888-777 66st".replace(reg,"");
// returns: 88877766
Also, use of with is not recommended
as it may be the source of confusing bugs and compatibility issues
MDN reference
Instead of
if (field.match(/^\d{9}/))
use this
if (!field.match(/\d{9}/))

how to validate cell number

i have to validate the cell no and my requirements are :
1.filed must not empty
2. if user enter alphabetic value it pop-up "alphabets are not allowed"
3. field must start with "+" sign
4. if filed value is less than 13 it pop-up "please enter valid phone no"
i am using this code..
function validateForm()
{
var cell = document.reg_form.cellno.value;
if(cell.length==0)
{
alert("Please enter cell number");
reg_form.cellno.focus();
return false;
}
if(isNaN(cell)||cell.indexOf(" ")!=-1)
{
alert("Enter numeric value")
return false;
}
if (cell.charAt(0)!="+")
{
alert("Cell no should start with +");
return false
}
if(cell.length < 13)
{
alert("You have entered wrong number");
reg_form.cellno.focus();
return false;
}
return true;
}
some code is not working here
when i enter numeric value.. it shows {"Cell no should start with "+"}
when i put {+} sign it says please enter numeric value
when i enter only single numeric value like {9} it goes forward.. although in this way field has only 2 value "+" and "9".. it should pop-up {"You have entered wrong number"}
please tell me where i made the mistake....
Your comparison of the cell length with 13 returns true (and alerts) if the value is longer than 13. I suspect you wanted
if(cell.length < 13)
A regular expression that matches only a plus sign and 12 digits:
function validateForm(){
var cell = document.reg_form.cellno;
return /^\+\d{12}$/.test(cell.value);
}
function validateForm()
{
var cell=document.reg_form.cellno.value;
var msg="";
if(cell.length==0)
{
msg="Please enter cell number";
alert(msg);
reg_form.cellno.focus();
return false;
}
if(isNaN(cell)) msg+="\nEnter numeric value";
if (cell.charAt(0)!="+") msg+="\nCell no should start with +";
if(cell.length != 13) msg+="\nCell number must be within 13 characters";
if(msg)
{
alert((msg));
reg_form.cellno.focus();
return false;
}
return true;
}
An example is here.

How do I validate a phone number with javascript?

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.
function validateFeedback() {
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for (i = 0; i < phone.length; i++); {
if (validNumber.indexOf(phone.charAt(i)) == -1); {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
Thanks so much for any help.
Regular expressions should help ;)
I'm sorry I haven't tried to run this code, but it should be OK.
function validateFeedback(){
var phone = document.getElementById("phone");
var RE = /^[\d\.\-]+$/;
if(!RE.test(phone.value))
{
alert("You have entered an invalid phone number");
return false;
}
return true;
}
try like this:
function validateFeedback()
{
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for(i = 0; i < phone.length; i++) {
if(validNumber.indexOf(phone.charAt(i)) == -1) {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
there are ; out of place ...
I think you should use a regex to do this. Something link this:
function validateFeedback() {
var phone = document.getElementById("phone").value;
var reg = new RegExp("[0-9 .-]*");
return reg.test(phone);
}
If the text input is in a form, you can reference it more directly using the form id and the element id:
var phone = document.<formId>.phone;
What you want to test is the value of the element, so you need:
var phone = document.<formName>.phone.value;
Since the function is probably called from a submit listener on the form, you can make things more efficient using:
<form onsubmit="return validateFeedback(this);" ...>
It also seems to me that a phone number has only digits, not "-" or "." characters, so you should only test for digits 0-9.
So the function can be like:
function validateFeedback(form) {
var phoneValue = form.phone.value;
// Use a regular expression to validate the value
// is only digits
if (/\D/.test(phoneValue) {
// value contains non-digit characters
// advise user of error then
return false;
}
}
you may want to test that the length is reasonable too, but note that phone numbers in different places are different lengths, depending on the location and use of area or country codes, and whether the number is for a mobile, landline or other.
I would prefer to use regular expressions for something like this.
Please look at my modified version of your function which should work in all major browsers without any framework.
function validateFeedback() {
// Get input
var phone = document.getElementById("phone"),
// Remove whitespaces from input start and end
phone = (phone || '').replace(/^\s+|\s+$/g, ''),
// Defined valid charset as regular expression
validNumber = "/^[0123456789.-]+$/";
// Just in case the input was empty
if (phone.length == 0) {
// This depends on your application - is an empty number also correct?
// If not, just change this to "return false;"
return true;
}
// Test phone string against the regular expression
if (phone.match(validNumber)) {
return true;
}
// Some invalid symbols are used
return false;
}
Try this one
function validateFeedback(value) {
var length = value.length;
chk1="1234567890()-+ ";
for(i=0;i<length;i++) {
ch1=value.charAt(i);
rtn1=chk1.indexOf(ch1);
if(rtn1==-1)
return false;
}
return true;
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

Categories

Resources