javascript return value Part 2 - javascript

Had some great help yesterday, and have a followup question/problem. Regarding an HTML form, when the user clicks onSubmit="return outer()", the function 'outer' only returns one of the two functions inside (either checkname or checkpostal). How do I get it to check both functions? Noob question I'm sure, but I want to understand, and not just copy paste from the plethora of forms out there.
var postalconfig = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
function outer() {
function checkname(f_name) {
if (document.myform.f_name.value == "") {
alert("Enter your First Name");
return false;
} else {
alert("valid First Name");
return true;
}
}
return checkname();
function checkpostal(postal_code) {
if (postalconfig.test(document.myform.postal_code.value)) {
alert("VALID postal");
return true;
} else {
alert("INVALID postal");
return false;
}
}
return checkpostal();
} //end of outer
The HTML:
<form name="myform" action="index.php" onSubmit="return outer();" method="post">
First Name
<input name="f_name" type="text" />
<br />
Telephone
<input name="telephone" type="text" />
<br />
<input name="Submit" type="submit" value="Submit Form" >
</form>

the execution of the function outer() stops whenever your return.
try this single return statement:
return checkname() && checkpostal();

When you write return checkname();, your function stops immediately.
There is no way to return a value and then run the rest of the function.
Instead, you need to call both inner functions, then use logical operators to combine them into a single boolean.
For example:
return checkname() && checkpostal();

Just do something instead or the returns or at the end do.
return checkName() && checkPostal();

What you're doing is technically valid, though may I advise that you define the functions separately. Use outer simply to call them and check their values, so you'd have:
function outer(){
return (checkname() && checkpostal());
}
function checkname(){
// Code for checkname
}
function checkpostal(){
// Code for checkpostal
}

Related

Javascript - how to prevent form from sending with multiple validation checks?

It seems that you can prevent a form from sending if your validation check returns false.
I have:
<form name="registration" action="registration.php" onsubmit="return validate()">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
My validate() function in my javascript is made of multiple different checks though.
function validate() {
checkUsername();
checkPassword();
checkFirstname();
checkLastname();
checkBirthdate();
checkEmail();
checkPhone();
}
There might be a case where the user inputs valid data for all of them except one. If that's the case, how do I tell validate() to still send 'false' back to the form, so that it doesn't submit?
Edit: If anyone is still reading this, for some reason my form is still sending. I even changed my validate() function so the only statement is "return false;" Do I have a syntax error or something?
Edit2: I found another solution that is simple, even if a little archaic. It overcame an issue I had where the function was only evaluating the first check and returning.
function validate() {
var truth1 = checkUsername();
var truth2 = checkPassword();
var truth3 = checkFirstname();
var truth4 = checkLastname();
var truth5 = checkBirthdate();
var truth6 = checkEmail();
var truth7 = checkPhone();
return (truth1 && truth3 && truth5 && truth2 && truth4 && truth6 && truth7);
}
all your individual field validation functions should return a boolean.
then your overall form validation function will be
function validate() {
var checks = [
checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone,
].map(function(check) { return check(); });
return (checks.indexOf(false) === -1);
}
now ur validate function will return false if any field is invalid. true if all fields are valid
You can use Array.prototype.every() to call each function, if any function returns false, false will be returned from .every() call
<form name="registration" action="registration.php">
<!-- some inputs like: -->
<input type="text" id="username" name="username">
<input type="text" id="firstname" name="firstname">
<input type="text" id="lastname" name="lastname">
<!-- and some others... -->
</form>
function validate() {
return [checkUsername,
checkPassword,
checkFirstname,
checkLastname,
checkBirthdate,
checkEmail,
checkPhone].every(function(check) {return check()});
}
document.querySelector("[name=registration]")
.onsubmit = function(event) {
event.preventDefault();
if (validate()) { this.submit() }
else { // notify user which fields are invalid }
}
The "validate" function needs to return a "true" boolean result only when ALL of the individual check functions return a "true" result.
One way to do this is to modify each line in the current "validate" function to something like the following code.
bUsernameSts = checkUsername();
if !bUsernameSts { return false };
...
<other checks>
...
return true;
The only way the new "validate" function can return "true" is if all of the individual input validation checks were successful.

Form validation problems

I have a very strange problem. Inside form I have hidden input with value -1 and input field for username.
<form action="" method="POST" name="login" onSubmit="return Validate()">
<input type="text" id="username"/>
<input type="hidden" id="available" value="-1"/>
< input type="submit" value="Send"/>
</form>
On submit function Validate() checks value of username input which mustn't be empty, and Validate() also checks value of available input which mustn't be valued -1.
function Validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else if(b<0)
{
alert("Form isn't finished");
return false;
}
else
{
return true;
}
}
Problem is that Validate() works only if one condition is evalueted. If function Validate() contains only 1 var(a or b) and 1 if order(without else if) it works correctly. But when I put it like this, when Validate uses a and b variables and if, else if conditional order it won't work. Really od.. Thanks in advance...
In this case it works:
function Validate(){
var a=document.getElementById("username").value;
if(a=="" || a==null)
{
alert("Username cannot be empty");
return false;
}
else
{
return true;
}
}
<input type="hidden" id="available" value="-1"/>
Here the value is of string dataType. Whereas
else if(b<0) //b is string dataType
Hence it failed. so change it as
var b= Number(document.getElementById("available").value);
Try like this
HTML:
<form action="" method="POST" name="login">
<input type="text" id="username" />
<input type="hidden" id="available" value="1" />
<input type="button" value="Send" onClick="return Validate()" />
</form>
JS:
function Validate() {
var a = document.getElementById("username").value;
var b = Number(document.getElementById("available").value);
if (a == "" || a == null) {
alert("Username cannot be empty");
return false;
} else if (b < 0) {
alert("Form isn't finished");
return false;
} else {
document.login.submit(); //dynamically submit the form
}
}
If you are wanting to get error notifications for each input don't use if/else here, use multiple if's and set your errors
function validate(){
var a=document.getElementById("username").value;
var b=document.getElementById("available").value;
var errors = [];
if(a=="" || a==null){
errors.push("Invalid username");
}
if(b<0 || isNaN(b)){
errors.push("Invalid available value");
}
if(errors.length>0) {
//do something with errors (like display them
return false;
}
}
Using the else if one of them evaluates to true it will skip the others. For instance if the first one is empty or null then it will do that block and skip the others.
I was testing your code for IE and Firefox and it work. Just add parseInt when you get the value of var b.
var b= parseInt(document.getElementById("available").value);

javascript vs jQuery form validation

Hi I have a simple form validation before I submit the form.
the validation if working fine with simple javascript function but I try to use the jQuery but its not working with as expected.
Here is the code I am using:
JSP:
<form action="/newManager.do" onsubmit="return validateListPropFields()" method="post">
<input type="hidden" name="operation" value="saveNewPropManagerInfo"/>
<td>Name<span class="required">*required</span></td>
<td><input type="text" name="name" id="name" placeholder="John Doe" /></td>
<input type="image" src="../images/common/submit_property.png" alt="Submit"/>
</form>
Javascript works fine:
function validateListPropFields(){
var name = jQuery("#name").val();
if( name==""){
return false;
}
else{
return true;
}
}
JQuery doesnot works:
function validateListPropFields(){
jQuery.noConflict();
(function($) {
$(function() {
var name = jQuery("#name").val();
if( name==""){
return false;
}
else{
return true;
}
});
})(jQuery);
}
Here I want to understand what makes the jQuery to not to work as expected?
In case of jQuery your validateListPropFields() function does not return anything. In this function there is an anonymous function which returns true or false but that has no effect on the outer function.
Though I have no Idea why would you want to complicate things so much I made some adjustments to your code so that it would work:
function validateListPropFields(){
jQuery.noConflict();
return (function($) {
return (function() {
var name = jQuery("#name").val();
if( name==""){
return false;
}
else{
return true;
}
});
})()(jQuery);
}
By submiting this code I am not saying that this is a good way to do this. I just wanted to illustrate how to make those inner anonymous functions work for your outer function.
You must import the jquery library first
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
It works for me
function validateListPropFields() {
if ($("#name").val() == "") {
return false;
} else {
return true;
}
}

Validation values

I'm trying to validate my values for alphabets and numberic as well as checking from database. I have created a function of validation and declaring my onclick button with validation function.
Function:
<script>
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
}
return true;
}
</script>
Sample Form:
<form id="Student" name="Student" method="post" action="nextpage.php">
<input name="StudentID" type="text" id="StudentID" value="<?php echo $StudentID?>"/>
<input name="StudentName" type="text" id="StudentName" value="<?php echo $StudentName?>"/>
<input name="StudentAdd" type="text" id="StudentAdd" value="<?php echo $StudentAdd?>"/>
<input type="submit" name="submit" value="Submit" onclick="return validate();"/>
</form>
I have already declared return validate function instead of calling my nextpage.php. But nothing popup for any alert. Kindly advise.
Thanks
Try including your scripts after the body tag to make sure it only references elements after it has already been loaded. Then put return true inside the else statement.
function validate()
{
var StudentID= document.getElementById('StudentID').value;
var StudentName = document.getElementById('StudentName').value;
var StudentAdd = document.getElementById('StudentAdd').value;
if(StudentID.length ==0 || StudentName.length ==0)
{
alert("Please do not leave any blanks");
return false;
}
else
{
if(isNumeric(StudentID))
{ alert("correct") }
else { alert("Numbers only!"); return false;}
alert("Correct correct");
return true;
}
}
Instead of the submit button's onclick, move the function to the form's onsubmit, like:
<form onsubmit="validate()" ...>
For the part of the 'if' statement that returns true you may run into some issues with the alerts() as the browser will be trying to submit the form, but over all it should work.
There is no isNumeric() function in JavaScript (I get Uncaught ReferenceError: isNumeric is not defined). You have to create it on your own: Validate decimal numbers in JavaScript - IsNumeric()

Check if multiple functions are true, then do something

I am stuck on what I thought was a simple PEBCAK error on my part. I am trying to verify all of my functions are true before I submit a form, but cannot figure for the life of me what is wrong. Below is my javascript code:
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
function checkname())
{
if(name condition)
{
return true;
}
else {
return false;
}
}
function passwordcheck(){
if(password condition)
{
return true;
}
else {
return false;
}
}
html below:
<form id="newaccount" name="newaccount" method="post" onSubmit="accountcode.php">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New" onClick="return checknewaccount()"/>
</form>
When i click "New, nothing happens, and I know the accountcode.php is not running, because nothing happens on the database end and there are no errors reported.
To sum up, my question is how checknewaccount() does not work? Does it have something to do with how I am calling them?
I am new to javascript so if I am completely off on my implementation, I apologize. Thank you very much for the help!
you've got the form syntax wrong - onsubmit = the name of the js function to call, action = the url...
<form action="accountcode.php" id="newaccount" name="newaccount" method="post" onSubmit="return checknewaccount()">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New"/>
</form>
Fully tested code:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
The form in the above code will only submit if the textbox has a value of test
A slightly better implementation would be:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
if(emailvalid() && checkname() && passwordcheck()) {
return true;
} else {
document.getElementById('validation').innerHTML = 'Validation failed!';
return false;
}
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<div id="validation"></div>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
As this at least tells the user the form wasn't submitted. Even better would be to give the user a more detailed reason why but that's beyond the scope of this question...
This part's fine (I took the liberty of fixing the indentation):
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
Although you could improve it:
function checknewaccount(){
return emailvalid() && checkname() && passwordcheck();
}
This part is a syntax error (to put it mildly):
function emailvalid(), checkname(), passwordcheck(){
if(condition){
return true;}
else{return false;}
If that's not a real quote from your code, you'll have to update your question (though I may not be here by then to update this answer). Not much point in asking about code and then quoting pseudo-code in the question. (At the very least, the pseudo-code is missing the final }.)
The same sort of thing is true for your functions in the form:
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
That's fine (assuming that email condition is still psuedocode), but there's no need for the if:
function emailvalid()
{
return email condition;
}
In terms of "nothing happens," make sure you have debugging tools you can use. Chrome has Dev Tools built in, just press Ctrl+Shift+I. For Firefox, you can install the excellent Firebug. Recent versions of IE have dev tools built into them as well (for older versions you can download a free version of Visual Studio that can plug into the browser). Any of these will tell you about syntax and other errors, let you walk through your code statement-by-statement, etc., which is crucial to figuring out what's happening.
Here's a quickly dashed-off version of what I think you're trying to do. I wouldn't do it this way, but I've made the minimal changes to make it work:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<input type="text" id="email" name='q' onblur="emailvalid()">
<input type="text" id="username" onblur="checkname()" >
<input type="password" id="password" onkeyup="passwordcheck()">
<input type="submit" value="New">
</form>
Notes on that:
As Basiclife pointed out, your form code has issues. Those are fixed above.
Above I've used action="http://www.google.com/search" but of course for you it would be action="accountcode.php" (or at least, I think it would).
Use onsubmit for the form submission handler, not onclick on the submit button. You can't cancel a form submission reliably cross-brower via the submit button's onclick.
In onsubmit, make sure you use return — e.g., onsubmit="return checknewaccount()", not onsubmit="checknewaccount()" — because we want to make sure the event stuff sees the return value. We don't care if the event stuff doesn't see the return value of our other checks (onblur="emailvalid()"), but if we did, we'd need returns there as well.
Only one of the fields above has a name attribute; none of yours do. Only fields with name attributes get submitted with forms. I've only used one name for my example because I only want to submit one field to Google, but for your purposes, you're going to want name attributes on all three fields. This brief article has a discussion of id vs. name and what they're for. You sometimes want both.
I've put the attributes in all lower-case, which is best practice (and required if you want to use XHTML).
However, I've removed the / from the ends of the inputs. This is a bit off-topic, but at the apparent level you're working at, you don't want to try to use XHTML, use HTML. Using XHTML correctly is technically difficult, both in authoring and server configuration, and even then you have to serve it as tag soup to IE or it won't handle it properly. XHTML has its place, but in the vast majority of cases, there's no reason to use it.
With the above combined with the JavaScript below, there's no purpose whatsoever to the handlers on the individual fields. I've left them, though, because I assume you're doing more than just the checks below — there's an example further down showing those handlers doing something useful.
JavaScript:
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var element;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
return element.value.indexOf('#') > 0;
}
function checkname() {
var element;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
function passwordcheck() {
var element;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
Live copy
Things change slightly if the emailvalid, et. al., functions are going to do something to let the user know the fields are invalid, such as highlighting their labels:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<label>Email:
<input type="text" id="email" name='q' onblur="emailvalid()"></label>
<br><label>Username:
<input type="text" id="username" onblur="checkname()" ></label>
<br><label>Password:
<input type="password" id="password" onkeyup="passwordcheck()"/></label>
<br><input type="submit" value="New">
</form>
JavaScript:
function checknewaccount() {
var result;
// Because we're actually doing something in each of the
// three functions below, on form validation we want to
// call *all* of them, even if the first one fails, so
// they each color their field accordingly. So instead
// of a one-liner with && as in the previous example,
// we ensure we do call each of them:
result = emailvalid();
result = checkname() && result;
result = passwordcheck() && result;
return result;
}
function emailvalid() {
var element, result;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
result = element.value.indexOf('#') > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function checkname() {
var element, result;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function passwordcheck() {
var element, result;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function updateLabel(node, valid) {
while (node && node.tagName !== "LABEL") {
node = node.parentNode;
}
if (node) {
node.style.color = valid ? "" : "red";
}
}
Live copy

Categories

Resources