Javascript onclick form validation - javascript

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();" />

Related

check if input text field contains min val on submit

I have a pretty simple HTML web form...
I am taking the data and serializing to JSON (and will eventually send somewhere else. But, for now am using console.log for test).
When the user fills out the form, and then clicks submit; I would like to simply check the value of my input text field, and make sure the user has at-least entered a number higher then 0, but not 0.
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
I would like this validation to run before, my serialize function below it fires. Essentially, I want to check or validate this before data is sent. If the user enters 0, I don't want to send.
Below is my full JavaScript. (I still cannot get validate function as described above).
(function ($) {
$.fn.serializeFormJSON = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
$('form').submit(function (e) {
function validateForm(){ // would like to check before below fires for serialize
var form = document.getElementById("form"), inputs = form.getElementsByTagName("input"),
input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
// if the value is not a valid number or it's less than or equal 0
if(isNaN(input.value) || +input.value < 0) {
flag = false;
input.focus();
console.log("error!");
// break;
}
}
return(flag);
}
e.preventDefault();
var data = $(this).serializeFormJSON();
console.log(data);
});
Simple validate number input. Try this.
$("#submit").on("click", function(){
inputValue = $("input[name='age']").val();
var num = parseInt(inputValue);
if(isNaN(num) || num <= 0){
console.log(inputValue + " Invalid number!");
} else {
console.log(inputValue + " Valid number!");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<input type="button" id="submit" value="Submit"\>
To accomplish that, I'm (more or less) usually do this:
HTML
<form action="(action url)" id="form" method="post" onsubmit="return validateForm()">
//form contents
</form>
JS
function validateForm() { // would like to check before below fires for serialize
//var form = document.getElementById("form"), inputs = form.getElementsByTagName("input"),
//If you use jQuery, it more preferred to write like this:
var form = $('#form'), inputs = form.find('input'), input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
// if the value is not a valid number or it's less than or equal 0
if(isNaN(input.value) || +input.value < 0) {
flag = false;
input.focus();
console.log("error!");
}
//do the break
if (!flag) break;
}
if (flag) {
var data = $(this).serializeFormJSON();
console.log(data);
}
return flag;
}

javascript "if" statement returning false value when both values are equal

I was trying out an HTML/JS login system, (which was only a learning experience, not to be used in a real case) There is an if statement that should return true when someone entered the correct username and password, but it returned false, and I can't figure out why.
here is the code i used:
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["Adam", "Adam2"];
var passwordArray = ["12345", "54321"];
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
if (valid) {
alert("Logging in...");
window.location.href = "http://www.google.com";
return false;
}
var again = " tries";
if (count == 1) {
again = " try";
}
if (count >= 1) {
alert("Username and password do not match.");
count--;
} else {
alert("Username and password do not match. You are now blocked.")
document.login.username.value = "You are now blocked";
document.login.password.value = "You can not see this";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
}
<div class="container">
<div class="header">
<h1>Login Page</h1>
</div>
<form name="login" onsubmit="return validateForm();" method="post">
<ul>
<li>Username:
<input class="username" type="text" name="username">
</li>
<li>Password:
<input class="password" type="password" name="password">
</li>
</ul>
<input type="button" class="submit" value="Login" name="submit" onclick="validate()">
</form>
</div>
You are breaking the loop and your if(valid) code is within the for loop. You probably meant to have the if(valid) outside the for loop scope.
For example you can do:
valid = false;
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Logging in...");
window.location.href = "http://www.google.com";
return false;
}
Notice I closed the for loop.
Also notice you have an valid=true after the if statement. I assume you did it for debugging purposes, but make sure to remove it.
Its in your for loop. The logic after the valid credentials check is at a wrong place, it should be out of the for loop.
var count = 2;
function validate() {
var un = document.login.username.value;
var pw = document.login.password.value;
var valid = false;
var usernameArray = ["Adam", "Adam2"];
var passwordArray = ["12345", "54321"];
for (var i = 0; i < usernameArray.length; i++) {
if ((un == usernameArray[i]) && (pw == passwordArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert("Logging in...");
window.location.href = "http://www.google.com";
return false;
}
var again = " tries";
if (count == 1) {
again = " try";
}
if (count >= 1) {
alert("Username and password do not match.");
count--;
} else {
alert("Username and password do not match. You are now blocked.")
document.login.username.value = "You are now blocked";
document.login.password.value = "You can not see this";
document.login.username.disabled = true;
document.login.password.disabled = true;
return false;
}
}
<div class="container">
<div class="header">
<h1>Login Page</h1>
</div>
<form name="login" onsubmit="return validateForm();" method="post">
<ul>
<li>Username:
<input class="username" type="text" name="username">
</li>
<li>Password:
<input class="password" type="password" name="password">
</li>
</ul>
<input type="button" class="submit" value="Login" name="submit" onclick="validate()">
</form>
</div>
It is a very bad idea to implement login in javascript on the client side. Anyone can see your passwords.
That said, your problem is that you exit the loop as soon as you find a matching username and password. So your if statement is never reached.

Validation for names in a text input

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.

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.

retain form values onclick after javascript validation fails

This is part of an assignment. Everything that's supposed to work, already works, but there's something that bothers me. The only purpose of the code so far is to test our ability to validate from data. Anyway, right now the validate() function is attached to a submit button:
<input type="submit" value="Find Love" onclick="validate()">
When any validation fails, all the text boxes, drop downs, etc. are cleared, but I want them to retain their values and just focus on the first incorrect value (retaining their values is more important to me at this point). The actual Does that require some modification of the onclick function or a different function all together? Please help. If you need to see the javascript I can post that as well.
function validate()
{
var blnValid = true;
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!")
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!")
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!")
document.getElementById("txtAge").focus();
}
}
if(blnValid)
{
var strInput = document.getElementById("txtAge").value;
if(!isInt(strInput))
{
blnValid = false;
alert("You must enter a valid number in the age field.")
document.getElementById("txtAge").select();
}
}
if(blnValid)
{
if(document.getElementById("selUserGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
if(document.getElementById("selFindGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
blnChecked = false;
arRadio = document.forms[0].rdbAgeRange;
for (var i = 0; i < arRadio.length; i++)
{
if(arRadio[i].checked)
{
blnChecked = true;
break;
}
}
if (!blnChecked)
{
alert("You must select an age group.");
blnValid = false;
}
}
if(blnValid)
{
if(!document.getElementById("chkSkeeball").checked
&& !document.getElementById("chkAir").checked
&& !document.getElementById("chkCliff").checked
&& !document.getElementById("chkHamster").checked)
{
blnValid = false;
alert("You must select a hobby.")
}
}
return blnValid;
}
function isInt(strValue)
{
var validNums = "0123456789";
var blnIsNumber = true;
var tempChar;
for (var i = 0; i < validNums.length; i++)
{
tempChar = strValue.substr(i, 1);
if (validNums.indexOf(tempChar) == -1)
{
return false;
}
}
return true;
}
function isBlank(elementID)
{
if(document.getElementById(elementID).value.length == 0)
{
return true;
}
return false;
}
Your problem is actually your HTML. Nothing in your Javascript is going to clear the elements but because you're using onClick the form is actually submitting anyway. I assume that it probably just submits back to the page and clears everything. Instead of onClick use onSubmit in the form element:
<form method="post" action="url_of_action" onSubmit="return validate()">
If it's not valid it will prevent the form from submitting.
Missing semi-colons:
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!") //here
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!") //and here
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!") //and here
document.getElementById("txtAge").focus();
}
}

Categories

Resources