Number validation in JavaScript - 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;
}

Related

Javascript validation condition fails

The below java script condition works in two condition but one of the condition is not working properly.
Page has a field which allow user to enter either without wildcard or with wild card with two characters For eg: PA% or PAGTHYUR
If the user enter PAGTHYUR in the Search Field still the else condition alert is calling "There is delay processing times for broad wildcard searches" instead of directly submit the "searchType".
How to avoid the else alert if the user enter direct value(for eg:PAGTHYUR)
My Script is as below:
if(manufNo!="") {
var strLen = manuNo;
var wild = "%";
if(strLen.indexOf(wild) != -1 && strLen.indexOf(wild) < 2) {
alert("Enter atleast two characters before wildcard");
return false;
} else {
alert ("There is delay processing times for broad wildcard searches");
}
searchType = "manufNo";
}
Thanks in advance
Add an extra else if in case there is no wildcard, you just gotta figure out what you want to happen in that case:
if(manufNo!=""){
var strLen = manuNo;
var wild = "%";
if (strLen.indexOf(wild) === -1) {
//code for what happens when there is no wildcard
// potentially nothing?
} else if (strLen.indexOf(wild) < 2){
//well place wildcard
alert("Enter atleast two characters before wildcard");
return false;
} else {
//badly placed wildcard
alert ("There is delay processing times for broad wildcard searches");
}
searchType = "manufNo";
}

password validation script is not working

I am using following script to validate password. Aims For validations are :
Password field should not be empty
Password Length should be between 6 and 10 characters
Password should not contain spaces and special characters
Password should be Alphanumeric.
But With following code , it passes first 3 aims but even after entering Alphanumeric text, it is till alerting:
"Password Should Contain Alphabet And Numbers Both".
Need your help
Code is :
if(document.subForm.password.value==""){
alert("Please Enter Your Desired Password....");
document.subForm.password.focus();
return false;
}
if(document.subForm.password.value.length < 6 || document.subForm.password.value.length > 10){
alert("Password Length Should Be In Between 6 And 10 Characters.");
document.subForm.password.focus();
return false;
}
var re = /^[\w\A-Z]+$/;
if(!re.test(document.subForm.password.value)) {
alert ("Your Password Has Spaces In Between The Words \n\nOr\n\nIt Contains Special Characters.\n\nThese Are Not Allowed.\n\nPlease Remove Them And Try Again.");
document.subForm.password.focus();
return false;
}
var realphanumeric = /^[a-z_A-Z_0-9]+$/;
if (!realphanumeric.test(document.subForm.password.value)){
alert("Password Should Contain Alphabet And Numbers Both");
document.subForm.password.focus();
return false;
}
Aragon0 suggested to use an open-source script from dropbox to check password strength. I recommend checking it out.
If you'd like one regular expresion to check everything:
^\w{6,10}$
Explanation:
From start (^ ) to end ($) of the string...
match only alphanumeric characters ([A-Za-z_0-9]),
with a length of 6-10 characters ({6-10})
If you want to force the user to have at least one number you can do that like this:
^(?![A-Za-z_]+$)\w{6,10}$
Your regex
/^[a-z_A-Z_0-9]+$/
doesn't do what you want. It will match the password "Test" but not "te#st".
You could use two regexes, which both need to match:
/[a-zA-Z]+/
/[0-9]+/
Btw, you should not enforce alphanumeric passwords or length constraints. You could use Dropbox's password strength script (https://github.com/dropbox/zxcvbn)
Some sample code with zxcvbn:
<script src="//cdn.jsdelivr.net/zxcvbn/1.0/zxcvbn-async.js" />
<script>
var result = zxcvbn(document.subForm.password.value);
if(result.entropy<56) // 56 is very secure, you could also lower it to 48 if you need to.
{
alert("Your password is too weak. It would be cracked " + result.crack_time_display);
return false;
}
</script>

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}/))

Check If only numeric values were entered in input. (jQuery)

I would like to check if users enter correct phone number in, with help of jQuery, so far I got to this stage:
var phone = $("input#phone").val();
if (phone !== "") {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
Basically it checks if phone number was entered and if it was, I would like to check if it is a numeric value and if it is not display the error messages.
Could anyone help with checking if it is numeric?
Try this ... it will make sure that the string "phone" only contains digits and will at least contain one digit
if(phone.match(/^\d+$/)) {
// your code here
}
There is a built-in function in jQuery to check this (isNumeric), so try the following:
var phone = $("input#phone").val();
if (phone !== "" && !$.isNumeric(phone)) {
//Check if phone is numeric
$("label#phone_error").show(); //Show error
$("input#phone").focus(); //Focus on field
return false;
}
You can use jQuery method to check whether a value is numeric or other type.
$.isNumeric()
Example
$.isNumeric("46")
true
$.isNumeric(46)
true
$.isNumeric("dfd")
false
I used this to check if all the text boxes had numeric values:
if(!$.isNumeric($('input:text').val())) {
alert("All the text boxes must have numeric values!");
return false;
}
or for one:
$.isNumeric($("txtBox").val());
Available with jQuery 1.7.
http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS
Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.
If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.
I used this:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
I hope this code may help you.
in this code if condition will return true if there is any legal decimal number of any number of decimal places. and alert will come up with the message "Right Number" other wise it will show a alert popup with message "Please enter only numbers into amount textbox.".
Thanks... :)
for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/
$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
text = window.getSelection().toString();
} if(index>=0&text.length>0){
}else if(index>=0&longeur<10){
}else {return false;} });
I used this kind of validation .... checks the pasted text and if it contains alphabets, shows an error for user and then clear out the box after delay for the user to check the text and make appropriate changes.
$('#txtbox').on('paste', function (e) {
var $this = $(this);
setTimeout(function (e) {
if (($this.val()).match(/[^0-9]/g))
{
$("#errormsg").html("Only Numerical Characters allowed").show().delay(2500).fadeOut("slow");
setTimeout(function (e) {
$this.val(null);
},2500);
}
}, 5);
});
This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.
Here is a function I have worked on that when set to the onInput event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.
<input oninput="formatPhone()">
function formatPhone(e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}

Validating textbox entry through javascript

I wanted to allow only characters in a textbox and space in between two characters.I am trying to avoid any unwanted characters and blank string in following Javascript code.
var filter = "^[a-zA-Z''-'\s]{1,40}$";
var label = $('#<%= txtName.ClientID %>').val();
if ((label.length > 0) && (label!= '')) {
if (label.match(/^[a-zA-Z \s]{1,40}$/)) {
if (label.match(/^\s$/)) {
alert("Please Enter a Valid name");
return false;
}
else {
$("#myModal").dialog('open');
}
}
else {
alert("Please Enter a Valid name");
}
}
else {
alert("Please Enter a Valid name");
}
This is working fine for everything except when user enters more than 1 space in the textbox. I was thinking that label.match(/^\s$/)) will take care of blank string or blank spaces.
Thanks
It looks like this is a job for 0 or more (the RegEx *)! (Pardon the exclamation, I'm feeling epic this morning)
/^\s$/ means "contains only one space"
I believe you are looking for
/^\s*$/ means "contains only zero or more spaces"
you should use + sign in regular expression for more than one entities.suppose if you want multiple spaces then use like var expr=/(\s)+/

Categories

Resources