javascript form validation not doing anything - javascript

i am trying to ensure an in put the contents of an input field is within an allowable number of character and if it is not print out an error message after the input field. the bellow js is contained in an external js file.
function validateForm()
{
var err_msg = getElementById('feedback_msg_first_name').value;
var first_name = getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}
The basic markup
<script type="text/javascript" language="javascript" src="client_form_val.js"></script>
</head>
<body>
<form id="register" name="register" action="includes/register.inc.php" method="post" onsubmit ="return validateForm();">
<label class="label">First Name:</label> <input type="text" name="first_name" id="first_name" /><br />
<span id="feedback_msg_first_name"></span>
the form is simply submitting without anything happening. where an I going wrong? any help would be appreciated.

Have a look at the following http://jsfiddle.net/VL7dc/2/
Rather than explaining where your going wrong, think you need to try and understand why this works and your doesnt.
function validateForm() {
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2) {
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
} else {
err_msg.innerHTML = '';
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}

You are calling the function when keyup event is fired in form. As a result when a user start typing his/her name after typing a single character this will show the error message.
Instead of calling the function when keyup event is fired, call the function when some button click happens (When the whole first name is typed).

You are forgetting to do document.getElementById. Firebug is giving errors on that

Getting errors:
Uncaught ReferenceError: getElementById is not defined
When you fix the missing documents you get this
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
Reason for the second is this
var err_msg = getElementById('feedback_msg_first_name').value; <-- string
err_msg.innerHTML = 'first name cannot contain less than 2 characters'; <--performing innerHTML on string

Try this
function validateForm()
{
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}

Related

form validation using isNaN()

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div class="basic">
<form id="input">
<p id="content">
<label> Birth Year: <input type="text" id="box1" placeholder="E.g. 1020" ></label> <br></br>
<!-- oninvalid="this.setCustomValidity('Please enter a number.')" -->
<label> Current Year: <input type="text" id="box2" placeholder="E.g. 1220" ></label> <br></br>
<input type="button" value="Calculate" id="submit" onclick="calculateAge(document.getElementById('box1').value, document.getElementById('box2'.value))"/>
</p>
</form>
</div>
<script type="text/javascript">
//previous attempt at form validation and bubble error message.
//error message for form fields
var birth = document.getElementById('box1');
birth.oninvalid = function(event)
{
event.target.setCustomValidity('Please enter a number.');
}
var current = document.getElementById('box2');
current.oninvalid = function(e)
{
e.target.setCustomValidity('Please enter a number.');
}
//function parameters do not have types?
function calculateAge(birthYear, currentYear)
{
var a = birthYear.match("^[0-9]+$").length == 1;
var b = currentYear.match("^[0-9]+$").length == 1;
//var check1 = Number.isInteger(birthYear);
//var check2 = Number.isInteger(currentYear);
var page = document.getElementById("content");
// fire off an error message if one of the two fields is NaN.
if (a ==true && b==true)
{
//var page = document.getElementById("content");
var content = page.innerHTML;
var age = currentYear-birthYear;
var stage;
if (age <18)
{
stage = "Teenager";
}
else if (age >= 18 || age <= 35)
{
stage = "Adult";
}
else
{
stage = "Mature Adult";
}
// \n not working at all...why?
var outputMessage = "Your stage is: " + stage + ".\n" + "Your age is: " + age + "." + '\n';
var node = document.createTextNode(outputMessage);
page.insertBefore(node, page.firstChild);
}
else
{
var outputMessage = "Error: please enter a number.";
var node = document.createTextNode(outputMessage);
page.insertBefore(node, page.firstChild);
}
}
var button = document.getElementById("submit");
button.onclick = function()
{
value1 = button.form.box1.value;
value2 = button.form.box2.value;
calculateAge(value1, value2);
}
</script>
</body>
</html>
I tried "adopting" some of the example code for form validation and my code refused to give me a little bubble that says something along the lines of "wrong input!" like the example code on the documentation had, so i decided to go with a simpler approach.
My goal is to check if the inputs from the form fields are number (no letters/symbols), so im doing an if check to do what i want the form result to do (output the stage/age of the person given their info), else I just want it to fire off a generic error message.
However, the error message does not get fired off even if the "age" output is "NaN". for example filling in box1 with a letter and box 2 with a number, you get stage: (blank) age: NaN. What am I missing?
Edit: implemented suggested change, and changed if check condition.
As you said, you have to validate the input first by checking if it is a number, since you cant calculate strings with numbers obviously.
Take a look at Number.isInteger(value), this is what you need. ;)
Here an overview of its outputs:
Number.isInteger(0); // true
Number.isInteger(1); // true
Number.isInteger(-100000); // true
Number.isInteger(0.1); // false
Number.isInteger(Math.PI); // false
Number.isInteger(Infinity); // false
Number.isInteger(-Infinity); // false
Number.isInteger("10"); // false
Number.isInteger(true); // false
Number.isInteger(false); // false
Number.isInteger([1]); // false
Edit: [Additions]
Also your code is wrong.
// fire off an error message if one of the two fields is NaN.
if (check1 ==true || check2==true)
isNaN(testValue) returns true if testValue is not a number. So what you do in your code is, you check if check1 OR check2 is not a number and if yes, you continue. I dont think thats what you wanted? Because in the else is your error message, and this else will only be called when both are false (means both of them must be not NaN's and this means you write the error exactly then when all is right)
Correct you should ask, when using IsNaN:
if(check1 == false && check2 == false) {
// Everything okay - No error
} else {
// One of them, or both, is not a number - Print error
}

why these two functions don't want to run? [duplicate]

This question already has an answer here:
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 9 years ago.
I really don't know why these two functions - leave() & do() - don't run !
function leave()
{
var x = document.getElementById("x");
if(x.value == "")
{
alert("please enter your name");
x.focus();
}
}
function do()
{
var y = document.getElementById("y");
if (y.value = "enter your name here")
{
alert("enter your last name");
y.focus();
y.select();
}
}
here is my code: http://jsfiddle.net/BsHa2
thanks in advance
you have 3 problems:
1- which is in your jsfiddle options you have chosen to wrap all your code in the onLoad, so the functions are not in the global context, you can fix it as I have in the code below.
2- this line would set the value to the value of y input:
if (y.value = "enter your name here")
change it to
if (y.value == "enter your name here")
3- the other probelm is do is a reserved word, DO NOT USE reserved word, although it would do what you want in some browsers.
window.leave = function leave()
{
var x = document.getElementById("x");
if(x.value == "")
{
alert("please enter your name");
x.focus();
}
}
window.check = function check()
{
var y = document.getElementById("y");
if (y.value = "enter your name here")
{
alert("enter your last name");
y.focus();
y.select();
}
}
First do is a keyword so you can't use it as a method name - rename it to something like check
Second for inline event hadndlers the methods must be in global scope - Select body/head in the second dropdown in left panel in the fiddle
Demo: Fiddle
do is a reserved keyword. You can't use it as function name. Rename it to something else.
Secondly, inline event handlers must be defined in global scope. In your fiddle you have to select Wrap in head option
Third, = is assignment operator, to compare either use == and ===, error in line (y.value = "enter your name here")
Use
function do1()
DEMO
do is a reserved keyword. You can't use it as function name.
Also, you have a mistake here:
if (y.value = "enter your name here")
you need to check for equality:
if (y.value === "enter your name here")
As an aside, you should really consider giving your variables meaningful names and using unobtrusive event handlers:
<form id="myForm">
<label for="firstName">First Name:</label>
<input type="text" name="input" id="firstName" size="20">
<br/>
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" size="20" value="enter your name here">
<input type="button" id="check" value="Check!">
</form>
var firstName = document.getElementById("firstName"),
lastName = document.getElementById("lastName"),
checkButton = document.getElementById("check");
firstName.onblur = function(){
if (this.value === ""){
alert("please enter your name");
this.focus();
}
}
check.onclick = function(e){
e.preventDefault();
if (lastName.value === "enter your name here") {
alert("enter your last name");
lastName.focus();
}
}
fiddle

How to make input required

What I want is that when both fields i.e. fname and lname are kept empty, the pop-up window should show both messages i.e. "First name must be filled out", "Last name must be filled out".
What modifications do I need to do?
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("First name must be filled out");
document.myForm.fname.focus();
return false;
}
var y = document.forms["myForm"]["lname"].value;
if (y == null || y == "") {
alert("Last name must be filled out");
document.myForm.lname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">First name:
<input type="text" name="fname">Last name:
<input type="text" name="lname">
<input type="submit" value="Submit">
</form>
</body>
Perhaps this will give you some ideas about how to proceed:
function validateForm() {
var errors = [],
fname = document.forms["myForm"]["fname"],
lname = document.forms["myForm"]["lname"];
if (lname.value == "") {
errors.unshift("Last name must be filled out");
lname.focus();
}
if (fname.value == "") {
errors.unshift("First name must be filled out");
fname.focus();
}
if (errors.length > 0) {
alert("Cannot submit\n" + errors.join("\n"));
return false;
}
}
Demo: http://jsfiddle.net/MKdg5/
The first thing you'll notice is that it is easier to read because blocks are indented. Also:
You currently use document.forms["myForm"]["fname"] and document.myForm.fname to access the same field. Pick one way and use it consistently, or
Create a variable that references the field, fname, and then use fname.value and fname.focus()
Don't bother testing for null because the .value property never will be.
Instead of immediately alerting an error and returning, add the error text to an array and then at the end test if the array is empty.
You can go with Hthml 5 required. It's so much simpler and neat.
<form>
First name: <input type="text" name="fname" required="required">
Last name: <input type="text" name="lname" required="required">
<input type="submit" value="Submit">
</form>
Demo
Note: The required attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome. But it is not supported in Internet Explorer 9 and earlier versions, or in Safari.
Try to validate your field as:
if (!x || x.length == 0)
BAsed on your validateForm function, your code would never check the second field. When using the return statement, the function will stop executing, and return the specified value.
A solution is use nested if statements and check both fields in one conditional block
if (x==null || x=="")
{
if (y==null || y=="")
{
//codes for both are not validated
}
else
{
//codes for just x is not validated
}
}
else
if (y==null || y=="")
{
//codes for y is not validated
}
else
{
//codes for all validated
}
This way use of return statement in each block won't break your function execution

Passing an id through a function parameter

Trying to get a value of a textbox by passing the ID into a function parameter. Should be easy but can't wrap my head around it.
JavaScript:
function checkfield(id)
{
var field = document.getElementById(id);
if (isNaN(field) == true)
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(textbox);
field.select(textbox);
return false;
}
return true;
}
HTML:
<input type="text" id="numbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield('numbox19')"/>
Error Message
Error: Unable to get property 'value' of undefined or null reference
Your ID is 19, but you're passing numberbox19 to the Javascript function. There are also several syntax errors.
Try:
<input type="text" id="numberbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield(this)"/>
And Javascript:
function checkfield(field) // <-- we passed the field in directly from the HTML, using 'this'
{
alert(field.value);
if (isNaN(field.value)) // check the value, not the field itself!
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(); // not "field.focus(textbox);"
return false;
}
return true;
}
The good thing here is, if you ever decide to change the ID for any reason, you only have to change it in one place instead of two.
the id of your input is "19" not "numberbox19"

Wrapper Function not working properly (Javascript)

I have two functions: One the validates the information in name fields of a form, and another that takes the information in those fields and prints them out in an alert box. Separately these functions work fine. I have to call them both, so I created a wrapper function. The function runs, but it refreshes instead of focusing. The weird thing is, if I check the first field, everything is fine, including the .focus();, but when I try to validate the second field, .focus(); doesn't work and the page refreshes. Any help would be appreciated. (I tried to revise my first question to add this, but when I went to save it, nothing happend.)
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
}
function validate() {
//alert ("TEST!!!");
var first = document.getElementById('firstname').value;
if (first.length == 0 || first.length > 25) {
alert("Please enter your first name, no longer than 25 chracters.");
document.getElementById('firstname').focus();
return false;
}
var last = document.getElementById('lastname').value;
if (last.length == 0 || last.length > 25) {
alert("Please enter your last name, no longer than 25 characters.");
document.getElementsByName('lastname').focus();
return false;
}
var title = document.getElementById('title').value;
if (document.getElementById('title').selectedIndex == 0) {
alert("Please select your salutation");
document.getElementById('title').focus();
return false;
}
return true;
}
function concatinate() {
var first = document.getElementById('firstname').value;
var last = document.getElementById('lastname').value;
var title = document.getElementById('title').value;
var fullname = title + " " + first + " " + last;
var printFull = "Welcome, " + fullname;
alert(printFull);
}
<form name="name" form id="name" method="post" onsubmit="return main();">
Salutation: <select name="title" select id="title">
<option selected="Please Select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss">Miss</option>
</select><br><br>
First Name : <input type="text" input id="firstname" name="firstname">
Last Name : <input type="text" input id="lastname" name="lastname"><br><br>
<input type="submit" value="Submit"><br><br>
</form>
In your form, you have an erroneous attribute "form" in your <form>, "select" in the middle of the <select> tag, and "input" in the <input> tags. I'm not sure what they are there for, or whether they are causing you trouble, but you should get rid of them nonetheless.
Also, your problem is this line:
document.getElementsByName('lastname').focus();
document.getElementsByName() returns an array, and there is no focus() method on an array. This was causing your issue with validating the last name.
Change it to match your other focus() calls:
document.getElementById('lastname').focus();
I also removed the temporary variable in your main() method:
function main(form) {
if (validate()) {
concatinate();
return true;
}
return false;
}
Working Demo: http://jsfiddle.net/cFsp5/4/
Your main function must return false if validation doesn't pass. Otherwise, it will return undefined, and the form will submit anyway (which is what you describe). So a simple fix would be:
function main() {
var test = validate();
if (test == true) {
concatinate();
return true;
}
return false;
}
http://jsfiddle.net/LhXy4/

Categories

Resources