Validation for names in a text input - javascript

I have a text input for a name. I want to allow only letters and non-consecutive white-spaces anywhere, except that white-space isn't allowed at the start or end of the input. So I have to invalidate numbers, symbols, and consecutive white-space.
Examples:
rohit_kumar_mehta
rohit__kumar_mehta
rohit_kumar__mehta
_rohit_kumar_mehta
__rohit_kumar_mehta
rohit_kumar_mehta_
_ -- means single white-space
__ -- means double white-space
String 1 is right.
Strings 2, 3, 4, 5, and 6 are wrong.
I tried the following code:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.myForm.fname.value;
var spacepos = x.indexOf(" ");
var numbers = /^[0-9]+$/;
var n = x.split(" ");
//x.innerHTML = n[0];
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?0123456789";
for (var i = 0; i < x.length; i++) {
if ((iChars.indexOf(x.charAt(i)) != -1)) {
alert("invalid...1");
return false;
}
/**else if ((numbers.indexOf(x.numberAt(i)) != -1) && spacepos > 0) {
alert("invalid...3");
return false;
}**/
}
var alphabets = /^[a-zA-Z]+$/;
if ((n[0].match(alphabets) && spacepos > 0)) {
alert("doublke space......1");
}
/*else if ((n[1].match(alphabets) && spacepos > 0)) {
alert("doublke space.....2");
}*/
else if ((x.match(alphabets) || spacepos > 0)) {
alert("ok..2");
return true;
}
else {
alert("invalid..2");
return false;
}
/**if(x==" ") {
alert("invalid..3");
return false;
}
else {
alert("ok...3")
return true;
}**/
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

Your function may be something like this:
function validateForm() {
var value = document.myForm.fname.value;
if(value.match(/^[a-zA-Z]+(\s{1}[a-zA-Z]+)*$/)) {
return true;
} else {
alert('Wrong name');
return false;
}
}
This function will allow to enter names that consist of one or more words without numbers and special characters, having one space between words and without starting or trailing spaces.
Example here http://jsbin.com/iducuq/1/edit

Try validateNameField() method, may this help you...
function validateNameField() {
$value = $('#name').val();
if(/^[a-zA-Z]+(\s{1}[a-zA-Z]+)*$/.test($value)) {
alert('Acceptable valid Name');
} else {
alert('invalid Name');
}
}

Try to analyze the string in a reverse manner:
function stripInvalidChars(input){
var re = /[a-zA-Z]+/g;
var match = new Array();
match = re.exec(input);
return match.join(' ');
}
This function will match only the valid characters (trimming spaces).
Then you can check the original string against this new string, if they are the same the string is valid.

Related

Masking With Phone Number Formats With Spaces

I have already a code that format it to the correct number format but the problem is
1.The position of the number input after the first and second hyphen don't have correct position. Sample. When i Input 12345 after the first (-) it will be 123465 The position got swap.
2. The user cannot add in the middle of the number if it already reach the maximum number which. What is happening right now is if i click on the middle of the text box i can add numbers and all the last parts are replaced.
JSFIDDLE CODE
HTML + JS
Telephone: <input type="text" value="____-___-___" data-mask="____-___-___"/><br/>
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);
function applyDataMask(field) {
var mask = field.dataset.mask.split('');
// For now, this just strips everything that's not a number
function stripMask(maskedData) {
function isDigit(char) {
return /\d/.test(char);
}
return maskedData.split('').filter(isDigit);
}
// Replace `_` characters with characters from `data`
function applyMask(data) {
return mask.map(function(char) {
if (char != '_') return char;
if (data.length == 0) return char;
return data.shift();
}).join('')
}
function reapplyMask(data) {
return applyMask(stripMask(data));
}
function changed() {
var oldStart = field.selectionStart;
var oldEnd = field.selectionEnd;
field.value = reapplyMask(field.value);
field.selectionStart = oldStart;
field.selectionEnd = oldEnd;
}
field.addEventListener('click', changed)
field.addEventListener('keyup', changed)
}
HTML:
<input id="txtPhone" data-mask="(___) ___-____" type="text" />
Javascript:
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);
function applyDataMask(field) {
var mask = field.dataset.mask.split('');
// For now, this just strips everything that's not a number
function stripMask(maskedData) {
function isDigit(char) {
return /\d/.test(char);
}
return maskedData.split('').filter(isDigit);
}
// Replace `_` characters with characters from `data`
function applyMask(data) {
return mask.map(function (char) {
if (char != '_') return char;
if (data.length == 0) return char;
return data.shift();
}).join('')
}
function reapplyMask(data) {
return applyMask(stripMask(data));
}
function changed(e) {
var i = field.value.indexOf('_');
if (e.keyCode == undefined) {
i = 0;
}
field.value = reapplyMask(field.value);
field.selectionStart = i;
field.selectionEnd = i;
}
field.addEventListener('click', changed)
field.addEventListener('keyup', changed);
}

Phone masking function inserting extra "x's" in form field

My phone masking script is inserting the correct dashes but for numbers with extensions it is adding extra "x's" after the 12th character. I am trying to format the mask so it looks like 000-0000x0000000 but it is returning 000-000-0000xxxx0000. Any idea on what I am doing wrong?
$(document).ready(function() {
var phoneNumber = $('#phone_number');
// Adds a phone number mask
phoneNumber.on('input paste', function(e) {
var phoneNumStr = e.target.value.split("-").join("");
// Create a new string with the hyphen
pro = phoneNumStr.split('').map(function(str, index) {
// Inserts a hyphen after the third and sixth characters
if (index == 3 || index == 6) {
return "-" + str;
} else if (index == 10) {
return "x" + str;
} else {
return str;
}
}).join('');
// Returns the new string
$(this).val(pro);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="phone_number">Phone Number*</label>
<input type="text" id="phone_number" name="phone_number" maxlength="20">
Changed your split '-' to use a regex to split on dash and x to remove the x's from the string that is evaluated.
$(document).ready(function() {
var phoneNumber = $('#phone_number');
// Adds a phone number mask
phoneNumber.on('input paste', function(e) {
//remove dash and x
var phoneNumStr = e.target.value.split(/[x-]/).join("");
// Create a new string with the hyphen
pro = phoneNumStr.split('').map(function(str, index) {
// Inserts a hyphen after the third and sixth characters
if (index == 3 || index == 6) {
return "-" + str;
} else if (index == 10) {
return "x" + str;
} else {
return str;
}
}).join('');
// Returns the new string
$(this).val(pro);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="phone_number">Phone Number*</label>
<input type="text" id="phone_number" name="phone_number" maxlength="20">
Try below code
$(document).ready(function() {
var phoneNumber = $('#phone_number');
// Adds a phone number mask
phoneNumber.on('input paste', function(e) {
var phoneNumStr = e.target.value.split("-").join("");
// Create a new string with the hyphen
pro = phoneNumStr.split('').map(function(str, index) {
// Inserts a hyphen after the third and sixth characters
if (index == 3 || index == 6) {
return "-" + str;
} else if (index == 10) {
if(str.indexOf("x")==-1)
return "x" + str;
else {
return str;
}
} else {
return str;
}
}).join('');
// Returns the new string
$(this).val(pro);
});
});

comma format as typing in angular

In jqxwidget
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxnumberinput/index.htm
by default the comma’s are already in place and separated by underscore.
what i want is to have the field empty and as soon as user starts typing the comma should come as and when similarly to F2 cell render-er.
so when typed 100 is should show 100
when typed 10000 ,it should show 10,000
also i have angular in my app as we are using jqxwidget in conjucation with so any angular way is also fine
one plugin i have found does the job but when focus out not when typing
https://www.npmjs.com/package/angular-numeric-directive
Hey I have solved this before by creating a directive that applies a filter to your HTML input. Here is a jsfiddle example
This is the directive. It both formats the user's input and keeps the cursor where the user is typing. My one issue with this is the logic behind where the cursor should be pointed.
fessmodule.directive('format', ['$filter', function ($filter) {
return {
require: '?ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
var parts = attrs.format.split(':');
attrs.foramtType = parts[0];
attrs.pass = parts[1];
ctrl.$formatters.unshift(function (a) {
return $filter(attrs.foramtType)(ctrl.$modelValue, attrs.pass)
});
ctrl.$parsers.unshift(function (viewValue) {
var cursorPointer = elem.context.selectionStart;
var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
elem.val($filter(attrs.foramtType)(plainNumber, attrs.pass));
elem.context.setSelectionRange(cursorPointer, cursorPointer);
return plainNumber;
});
}
};
And the HTML to activate it
<input type="text" ng-model="test" format="number:2" />
Angular already provides pretty basic formatting filters
like
html : {{val | number:0}}
script: $scope.val = 1234.56789;
ref:
https://docs.angularjs.org/api/ng/filter/number
https://docs.angularjs.org/api/ng/filter/currency
https://scotch.io/tutorials/all-about-the-built-in-angularjs-filters
Demo
<input value="100000000" id="testInput" />
Simply apply this .formatInput(numberOfCharactersForSeparator, Separator ); to your input
$(document).ready(function()
{
$("#testInput").formatInput(3,"," );
});
using this plugin that i just made :p
$.fn.formatInput = (function(afterHowManyCharacter,commaType)
{
if(afterHowManyCharacter && commaType != ".")
{
var str = $(this).val();
var comma = commaType != undefined ? commaType : "," ;
var strMod ;
if($(this).val().indexOf(".") == -1)
strMod = replaceAll(comma,"",$(this).val());
else
{
strMod = replaceAll(comma,"",$(this).val());
strMod = strMod.substring(0,strMod.indexOf("."));
}
if($(this).val().indexOf(".") != -1)
$(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )+ $(this).val().substring($(this).val().indexOf(".")));
else
$(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma ));
var nowPos = 0;
$(this).on("keyup",function(e)
{
nowPos = doGetCaretPosition($(this)[0]);
var codePressed = e.which ;
if(" 8 37 38 39 40 46 17".indexOf(" "+codePressed) == -1 && !e.ctrlKey)
{
if($(this).val().length >afterHowManyCharacter)
{
strMod ;
if($(this).val().indexOf(".") == -1)
strMod = replaceAll(comma,"",$(this).val());
else
{
strMod = replaceAll(comma,"",$(this).val());
strMod = strMod.substring(0,strMod.indexOf("."));
}
if($(this).val().indexOf(".") != -1)
$(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )+ $(this).val().substring($(this).val().indexOf(".")));
else
$(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma ));
if((strMod.length-1)%afterHowManyCharacter == 0)
{
setCursor($(this)[0],nowPos+1);
}
else
{
setCursor($(this)[0],nowPos);
}
}
}
});
}
else if( commaType == ".")
{
console.log("You can't use . as Separator");
}
function splitByLength(str,maxLength)
{
var reg = new RegExp(".{1,"+maxLength+"}","g"); ;
return reverseStringInArray(str.split("").reverse().join("").match(reg).reverse());
}
function replaceAll(find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
function reverseStringInArray(arr)
{
$.each(arr,function(i,val)
{
arr[i] = arr[i].split("").reverse().join("");
});
return arr ;
}
// Author of setCursor is nemisj
function setCursor(node,pos)
{
node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node){
return false;
}else if(node.createTextRange){
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange){
node.setSelectionRange(pos,pos);
return true;
}
return false;
}
// Author of setCursor is bezmax
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
});
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('app',[]);
app.controller('myCtrl',function($scope){
$scope.name = "1232.33";
$scope.changeFormat = function(value){
$scope.name = Number(value).toLocaleString('en');
}
});
</script>
<body>
<div ng-app="app" ng-controller="myCtrl">
<p>Input something in the input box:</p>
<p>Number: <input type="text" ng-model="name" placeholder="Enter name here" ng-blur="changeFormat(name)"></p>
<h1>Formatted value {{name}}</h1>
</div>
</body>
</html>
Here is a hackish solution. The idea is to watch for changes in the input text and format the input accordingly.
HTML
<div ng-controller="so">
<input ng-model="salary"></input>
</div>
Javascript
app.controller('so', function($scope) {
$scope.salary = '12567';
$scope.$watch('salary', function(){
// strip out all the commas and dots
var temp = $scope.salary;
if (!temp) return; // ignore empty input box
var lastChar = temp[temp.length-1];
if (lastChar === ',' || lastChar === '.') // skip it/allow commas
return;
var a = temp.replace(/,/g,''); //remove all commas
//console.log(a);
if (isNaN(a))
$scope.salary = temp.substring(0, temp.length-1); // last char was not right
else {
var n = parseInt(a, 10); // the integer part
var f = ''; // decimal part
if (a.indexOf('.') >= 0) // decimal present{
if (lastChar === '0') // 0's after decimal point are OK
return;
f = ('' + parseFloat(a)).substr(a.indexOf('.'));
}
var formatted_salary = '';
var count = 0;
var ns = '' + n; // string of integer part
for (var i=ns.length-1; i>=0; i--) {
if (count%3===0 && count>0)
formatted_salary = ',' + formatted_salary;
formatted_salary = ns[i] + formatted_salary;
count += 1;
}
formatted_salary = formatted_salary + (f ? f : '');
$scope.salary = formatted_salary;
}
})
})
Here is the JSFiddle
It gracefully handles things like
won't allow any characters other than numbers , and .
multiple commas and dots formatted correctly
PS:- you might want to handle the proper positioning of the caret yourself using text range. I haven't included that here.
100 => 100
1000 =>1,000
10000 => 10,000
100000 => 100,000
...
10000000 => 10,000,000
10000000.540 => 10,000,000.540
I use ng-change event to make this example
// on-change event
$scope.ngchanged = function (val) {
$scope.iputval = numberWithCommas(val);
};
function numberWithCommas(n) {
while (n.toString().indexOf(",") != -1)
{
n = n.replace(",", "");
}
var parts = n.toString().split(".");
return parts[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
}
Use it
<input type="text" ng-model="iputval" ng-change="ngchanged(iputval)" />
Updated add demo and code by following link
Full code and demo >> here
Please check out ng-number-input
I think it accomplishes the task easily.
https://www.npmjs.com/package/ng-number-input
I made it for my project and I thought I'd share it with the community.
Source code available on git hub and link is available in npm page.

HTML Form Validation Infinite Loop using an array of Functions

I am getting an infinite loop when pressing submit after filling in 3 / 7 of the form fields. I fill in the first and last name, and the email address.
Here is the function that I suspect the infinite loop is coming from:
function runValidation()
{
// Element Variables
var name_first = document.forms[0].elements["name_first"];
var name_last = document.forms[0].elements["name_last"];
var address_email = document.forms[0].elements["address_email"];
var address_number = document.forms[0].elements["address_number"];
var address_postal = document.forms[0].elements["address_postal"];
var url_link = document.forms[0].elements["other_website"];
var user_age = document.forms[0].elements["other_age"];
// Arrays of elements and functions
var userVariables = new Array(name_first, name_last, address_email, address_number, address_postal, url_link, user_age);
var userFunctions = new Array(valName, valName, valEmail, valNum, valCode, valLink, valAge);
var userFuncExec = new Array();
for (i = 0; i < userVariables.length - 1; i++)
{
userFuncExec[i] = userFunctions[i](userVariables[i]);
if ( userFuncExec[i] == false )
{
userVariables[i].value = "";
userVariables[i].focus();
return false;
}
}
// If the function has not returned false , then the form is valid;
document.forms[0].submit();
}
Here is the entire .js file:
http://pastie.org/5563532
// This is the validation for the contact form of Exquisite Taste
var debugOn = true; // toggles debug alerts.
function runValidation()
{
// Element Variables
var name_first = document.forms[0].elements["name_first"];
var name_last = document.forms[0].elements["name_last"];
var address_email = document.forms[0].elements["address_email"];
var address_number = document.forms[0].elements["address_number"];
var address_postal = document.forms[0].elements["address_postal"];
var url_link = document.forms[0].elements["other_website"];
var user_age = document.forms[0].elements["other_age"];
// Arrays of elements and functions
var userVariables = new Array(name_first, name_last, address_email, address_number, address_postal, url_link, user_age);
var userFunctions = new Array(valName, valName, valEmail, valNum, valCode, valLink, valAge);
var userFuncExec = new Array();
for (i = 0; i < userVariables.length - 1; i++)
{
userFuncExec[i] = userFunctions[i](userVariables[i]);
if ( userFuncExec[i] == false )
{
userVariables[i].value = "";
userVariables[i].focus();
return false;
}
}
// If the function has not returned false , then the form is valid;
document.forms[0].submit();
}
function valName(nam)
{
// This validates whatever name is passed.
if(nam.value.length > 1)
{
if(debugOn)
alert("Name is valid");
return true;
}else{
alert("Please enter a name that is at least 2 characters long.");
return false;
}
}
function valEmail(email)
{
// This function checks to see if the email address entered is valid.
// Check if the email field is less than 10 characters ( 3#3.2-3 = 10 - 11 characters for the shortest email address)
if ( email.value.length < 10 )
{
alert("Your email is too short to be valid.")
return false;
}
// Check to see the email has at least one period and one # symbol
if ( email.value.indexOf(".") < 0 || email.value.indexOf("#") < 0)
{
alert("The format of your email is invalid. All emails require a '.' and a '#'");
return false;
}
// Check if the last index of the '.' is after the '#' symbol & make sure there is only one index of '#'
if ( email.value.lastIndexOf(".") < email.value.indexOf("#") || email.value.indexOf("#") != email.value.lastIndexOf("#") )
{
alert("Your email is invalid and may have too many # symbols or have them in the wrong place");
return false;
}
// Check to see that the index of the last '.' has at least two characters after it.
if ( email.value.lastIndexOf(".") > email.value.length-3 )
{
alert("Your top level domain has to be at least 2 characters");
return false;
}
// Check to see if the split array has at least 3 characters in each section except for the last (TLD).
var email_attributes = new Array();
var email_attributes = email.value.split("."); // tiessen-b#webmail.uwinnipeg.ca
for ( i = 0; i < email_attributes.length - 2; i++ ) // -2 = (-1 so length = index; and -1 so the last section isn't included.)
{
// If one of the characters in the array value is '#' and the string length is < 3 then it isn't long enough.
if ( email_attributes[i].indexOf("#") > -1 )
{
// If the length of the string - 1 (for the '#') symbol is not considered a valid symbol.
if ( ( email_attributes[i].length - 1 ) < 3 )
{
alert("Your email doesn't have a long enough section");
return false;
}
}
}
// If it got this far it is probably a valid email address.
alert("Your email is valid!");
return true;
}
function valNum(num)
{
// This function validates a 10 or 12 digit phone number
var isNum = /[0-9]/; // If the value is a number
// Check to see if the number length is either 10 or 12
if ( num.value.length == 10 || num.value.length == 12)
{
// Make sure every character is a number.
for (i = 0; i < num.value.length; i++)
{
if ( !isNum.test( num.value.charAt(i) ) )
{
alert("You have entered an invalid number.");
return false;
}
}
}
else if ( num.value.length == 12 )
{
// split all numbers into an array with a delimiter of '-'
var numbers = num.value.split("-");
// check if the array length is not 3 or has 4 digits in the last section
if ( numbers.length != 3 || numbers[0].length > 3 || numbers[1].length > 3 );
{
alert("Your number is not formatted correctly. Make sure it is formatted like this: 204-290-9611.");
return false;
}
// loop through each section of the numbers array and make sure they are all numbers
for ( l = 0; l < numbers.length - 1; l++ )
{
for ( i = 0; i < numbers[l].length; i++)
{
if ( !isNum.test(numbers[l].charAt(i)) )
{
alert("Your phone number has invalid characters");
return false;
}
}
}
}else{
alert("Phone number is invalid");
return false;
}
if(debugOn)
alert("Phone number is invalid");
return true;
}
function valCode(code)
{
// This function validates a postal code.
var valid = true;
var isChar = /[A-z]/;
var isNum = /[0-9]/;
// Make sure the postal code is 6 characters long.
if( code.value.length != 6)
{
alert("Please enter a 6 digit/character postal code");
return false;
}else{
if ( !isChar.test( code.value.charAt(0) ) )
valid = false;
if ( !isNum.test( code.value.charAt(1) ) )
valid = false;
if ( !isChar.test( code.value.charAt(2) ) )
valid = false;
if ( !isNum.test( code.value.charAt(3) ) )
valid = false;
if ( !isChar.test( code.value.charAt(4) ) )
valid = false;
if ( !isNum.test( code.value.charAt(5) ) )
valid = false;
if (valid)
{
if(debugOn)
alert("Postal Code is valid");
return true;
}else{
alert("Your Postal Code is formatted incorrectly.");
return false;
}
}
}
function valLink(link)
{
if(link.value.length > 0)
{
linkParts = link.value.split(".");
if ( linkParts[0] == "www" || linkParts[0] == "http://www")
{
if( linkParts[linkParts.length-1].length < 2 || linkParts.length < 3)
{
alert("Invalid domain");
focusEmpty(link);
}else{
return true;
}
}else{
alert("invalid host");
focusEmpty(link);
}
}else{
return true;
}
}
function valAge(age)
{
// This function validates the users age.
var parsedAge = parseInt(age.value, 10);
if( age.value.length > 0 )
{
if( isNaN(parsedAge) )
{
alert("invalid age");
focusEmpty(age);
}else{
if(age.value < 1 || age.value > 125)
{
alert("Is that your real age? Please try again...");
focusEmpty(age);
}else{
return true;
}
}
}else{
// If the user doesn't submit anything return true and validate (Age is optional).
if(debugOn)
alert("Age is empty but valid.");
return true;
}
}
Here is the code for the HTML form:
<form method="post" enctype="text/plain" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi" name="contactForm">
<div>
<p>First Name:</p>
<input name="name_first" type="text" />
</div>
<div>
<p>Last Name:</p>
<input name="name_last" type="text" />
</div>
<div>
<p>Email Address:</p>
<input name="address_email" type="text" />
</div>
<div>
<p>Phone Number:</p>
<input name="address_number" type="text" />
</div>
<div>
<p>Postal Code:</p>
<input name="address_postal" type="text" />
</div>
<div>
<p>Website:</p>
<input name="other_website" type="text" />
</div>
<div>
<p>Age:</p>
<input name="other_age" type="text" />
</div>
<div style="text-align:right; margin-right:20px;">
<input name="submit" type="button" value="Send" onclick="runValidation();"/>
</div>
</form>
Why am I getting an infinite loop?
Use for (var i = 0;... in your loop definitions rather than for (i = 0.
Variable scope in javascript can be tricky to understand. The answer to What is the scope of variables in JavaScript? has a great explanation.

Javascript onclick form validation

Can someone tell me what I am doing wrong over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...
function ValidateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++) {
if(validChars.indexOf(val.charAt(i)) == -1)
alert('Please enter valid number');
return false;
}
return true;
}
<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >
Pay attention to the statement start and end - the "return false;" will terminate the "for" loop on the first iteration.
Correct code:
function ValidateNumeric() {
var val = document.getElementById("tbNumber").value;
var validChars = '0123456789.';
for(var i = 0; i < val.length; i++) {
if(validChars.indexOf(val.charAt(i)) == -1) {
alert('Please enter valid number');
return false;
}
}
return true;
}
format your if correctly, else it will consider only first statement.
for(var i = 0; i < val.length; i++) {
if(validChars.indexOf(val.charAt(i)) == -1)
{
alert('Please enter valid number');
return false;
}
}
Use regular expressions!
function validateNumeric() {
var val = document.getElementById("tbNumber").value;
var regex = /^[0-9\.]+$/;
if(regex.test(value))
return true
else {
alert("Please enter a valid number");
return false;
}
}
However, that regex allows 1.22.3.6...2 as an input, which is probably not desired. You probably want to have the regex ^(\d+(\.\d+)?|\.\d+)$
Also, HTML tags should be lower case, and attributes should be quoted:
<input type="number" id="tbNumber" />
<input type="submit" name="action" value="Save Changes" onclick="return validateNumeric();" />

Categories

Resources