javascript function inside function - javascript

I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}

So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.

I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...

Related

How do I display an error message if the input is wrong on HTML

Im trying to display an error message in RED beside the input field to let the user know, however I dont know why my error message is not working. The requirement for the input is starting with a capital letter, followed by non special characters (any alphabets) please help me see what is wrong with my code
I am still new to HTML and I know many people said about regex but im not sure i have not learn that
<html>
<script>
function validateForm() {
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
</script>
<style>
#errorName
{
color:red;
}
</style>
<form action="handleServer.php" method="get" onSubmit="return validateForm()">
<body>
<!-- starting with first name-->
First name: </br>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName"></br>
<input type="submit" value="Submit">
</body>
</form>
</html>
I see your if statements are not closed properly and also the input box.
Please find codepan
function validateForm() {
console.log(1);
var fname = document.getElementById("fname").value;
if (/^[A-Z]\D{2,30}$/.test(fname) == false)
{
document.getElementById("errorName").innerHTML = "Your email must be filled";
return false;
{
return name;
}
}
}
When i tend to use regex i store it in its own value like this:
const patternName = /[0-9]|[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/|#]/;
let resultName = patternName.test(name.value);
The code above checks if the name contains anything from the regex above and if it does resultName will return true.
Next we can do the following:
If name is empty you get an error and it contains anything from the regex above we. In this case we show the error
If resultName is true we know that name contains something from the regex, so that it's not a valid name.
If not we show success message
if (name.value === "" || resultName) {
showErrorName();
} else {
showSuccessName();
}`

JS->Form validation on inputs. Using for loop to get all the inputs index

I have a form with 4 inputs and I want to show an alert on submit. What I have done is that I have already created the warnings that goes under every input with display:none; in CSS.
After this I have created a for loop in JS to get the index of every input and apply my if statement of showing the the alert if === null || === ""
using a variable to make the querySelector("THE CLASS").style.display="block";
Also on my form I have this line
<form method="post" class="q-form" name="form" onsubmit="return validate()">
My problem is when I submit my form the only alert that is shown is the one under the Username and after it appears it also disappears because I think that the for loop goes to the next input.
Let me know if there is something more to clarify.
Here you have all the code: https://jsbin.com/kazopahuga/1/edit?html,js,output
If you want to see the alert showing press Run with JS
Thank You!
I suggest a few modifications to your validare() function:
Add a flag indicating whether the whole form is valid, assume it's true until you find an input that is invalid. Return the value of this flag.
var isValid = true;
Capture your validation messages too so you can access them by index like your inputs:
messages = document.getElementsByClassName(' alert alert-danger custom');
When you find an invalid input, display the associated message and update the valid flag to false.
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
Here is the updated function:
function validare() {
var inputs, messages, index;
var isValid = true;
inputs = document.getElementsByTagName('input');
messages = document.getElementsByClassName(' alert alert-danger custom');
for (index = 0; index < inputs.length; ++index) {
var currentInputValue = inputs[index].value;
if (currentInputValue == null || currentInputValue === "") {
messages[index].style.display = "block";
isValid = false;
}
}
return isValid;
}
Updated jsbin here
Here is an updated solution: jsbin
You used querySelector which return only the first element it finds with the same class, you should have used querySelectorAll which return all the selectors.

Checking multiple functions are true in Javascript before submission

I have been working on improving my javascript validation and with the help off the internet (including stackoverflow) have been able to create what I need. The only problem I have is checking multiple functions = true doesn't seem to work. It's been driving me crazy and I hope someone can help.
What I'm trying to do is check that the username and email are within the set variables and if the username and email haven't been used. The availability off the username and email shows whether it's available or not whilst you are typing. Which works great, the only problem is that if the user clicks register when they one or more are not available the form still gets submitted. To overcome this I thought off using an if statement that checks if multiple functions are true, if so pass the details to the php script if not the show an alert message.
For some reason it keeps bringing up the 'not available' alert message even if the username and email are showing as available on the form. I have checked the database table and the php code is working correctly.
Here is the code below
html:
<form name="regForm" role="form" action="php/registerphp.php" method ="post"
onsubmit="return RegFormValidation();">
<fieldset>
<div class="form-group">
<label for="username">Username</label><span>*</span><span> </span><span id="username_availability_result"></span>
<input type="username" class="form-control" id="username"
placeholder=" Enter a username" name="username">
</div>
<div class="form-group">
<label for="email">Email address</label><span>*</span><span> </span><span id="email_availability_result"></span>
<input type="email" class="form-control" id="email"
placeholder=" Enter email" name="email">
</div>
Javascript
function RegFormValidation()
{
if(check_username_availability() && check_email()) {
return true;
} else
{
alert("Username or Email not correct.");
return false;
}
}
$(document).ready(function username_correct_format()
{
var min_chars = 3;
var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
var characters_error = ' - Min. characters required is 3, only use letters and numbers.';
var checking_html = 'Checking...';
$('#username').keyup(function()
{
if($('#username').val().length > min_chars || characterReg.test($('#username').val()))
{
//else show the checking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_username_availability();
}else
{
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}
});
});
//function to check username availability
function check_username_availability()
{
var username = $('#username').val();
$.post("php/check_username.php", { username: username },
function(result)
{
if(result == 1)
{
//show that the username is available
$('#username_availability_result').html('<span class="is_available"> is available</span>');
return true;
}else
{
//show that the username is NOT available
$('#username_availability_result').html('<span class="is_not_available"> is not available</span>');
return false;
}
});
}
$(document).ready(function email_correct_format()
{
var min_chars = 4;
var characters_check = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var characters_error = ' - only 1 email address per user.';
var checking_html = 'Checking...';
$('#email').keyup(function()
{
if($('#email').val().length > min_chars && characters_check.test($('#email').val()))
{
//else show the cheking_text and run the function to check
$('#email_availability_result').html(checking_html);
check_email();
}else
{
//if it's bellow the minimum show characters_error text '
$('#email_availability_result').html(characters_error);
}
});
});
//function to check email availability
function check_email()
{
var email = $('#email').val();
$.post("php/check_email.php", { email: email },
function(result)
{
if(result == 1)
{
//show that the email is available
$('#email_availability_result').html('is available ');
return true;
}else
{
//show that the email is NOT available
$('#email_availability_result').html('<span class="is_not_available"> is already registered.</span>');
return false;
}
});
}
Because your checks are done using asynchronous methods your check methods are going to return before the requests have been made, your functions also do not return anything anyways. Thus each one is going to be returning undefiend
You can use jQuery's .when method to wait for one or more requests to be completed and then execute some function.
First thing that will need done is pass the event object and the form object to the validation function. We will need the event object to call preventDefault so that the form will not submit before it is supposed to.
Then we need to change the validation function around so that it will call the two check functions and setup a promise to call a callback when they are complete.
We will also need to change your to check functions to return the promise object that the .post method returns so that the .when method can use them.
After that you just do your checks against the returned data and process.
HTML
<form name="regForm" role="form" action="php/registerphp.php" method ="post"
onsubmit="return RegFormValidation(event,this);">
Javascript
function RegFormValidation(e,form) {
//Prevent the form submission
e.preventDefault();
//Each check function returns a promise object
jQuery.when(check_username_availability(),check_email())
.done(function(usernameResponse,emailResponse){
//the responses passed back to the callback will be in an array
//element 0 is the actual data retrieved
//element 1 is the status (success, error, etc)
//element 2 is the promise object
if(usernameResponse[0] == 1 && emailResponse[0] == 1){
//if everything is ok manually submit the form
form.submit();
} else {
alert("Username or Email not correct.");
}
});
}
function check_username_availability() {
var username = $('#username').val();
return $.post("php/check_username.php", { username: username })
.then(function(data){
if(data == 1) {
$('#username_availability_result').html('<span class="is_available"> is available</span>');
} else {
$('#username_availability_result').html('<span class="is_not_available"> is not available</span>');
}
//We have to return the data here to make sure it gets passed
//to the done callback from the validation function
return data;
});
}
function check_email() {
var email = $('#email').val();
return $.post("php/check_email.php", { email: email })
.then(function(data){
if(data == 1) {
$('#email_availability_result').html('<span class="is_available"> is available</span>');
} else {
$('#email_availability_result').html('<span class="is_not_available"> is not available</span>');
}
//We have to return the data here to make sure it gets passed
//to the done callback from the validation function
return data;
});
}
You can look at jQuery's api section Deferred Objects to learn more about their deferred/promises. You can also look at other promise libraries like Q and see how they work, as they tend to work on the same principles and use similar method names.
You dont have to wrap functions in
$(document).ready();
this will change the scope of function calling/referencing and is not a good practice. As this might help you out in resolving the return value from the function.
All the Best!
To do multiple boolean checks, I would create a global variable (eg, allValid) immediately set to your control value (true or false)... then on each validation function, change the variable ONLY if something is invalid, so:
var allValid = true;
if(!/*validation requirement*/) { allValid = false; }
allValid = anotherValidationFunction() || false;
if(!allValid) { /*something's invalid*/ }
I don't know if that makes sense.
It looks like you're making ajax calls for your validation. My guess is these are asynchronous calls (which won't work with your code).
My guess (sorry, I don't have time to test) is your functions check_username_availability and check_email will immediately return "undefined", which is why your validation is always throwing the alert.
Instead, what you'd want to do is make synchronous calls, or use callbacks to invoke the necessary functions.
A couple of things you could do to improve your code.
You probably don't have to make two separate requests, pass the username and email direct to your php code, and you'll save on HTTP requests going out.
onsubmit="return RegFormValidation();" should be changed in jQuery to a bind call. Give the form an ID and do something like this
<form id="registerForm">....
$("form#registerForm").on('submit', function(e){
});
You've got var username = $('#username').val();
then
if($('#username').val().length > min_chars || characterReg.test($('#username').val()))
{
You could probably clean that up a bit and reuse the variable, rather than continued calls to the jQuery functions. Patrick's answer above is a good start to some tidy ups and I reckon addresses the overall problem you are experiencing.

form validation javascript stop new window from opening

I have written a large page including a form as my first JavaScript project. I've gotten some help here, so thanks. I am very happy with what I have so far, but I have one last problem I need to deal with.
The code I will submit here is a tester. I have a couple of functions attached to an onClick new window. What happens is user submits form and their info appears in a new window. (My original page is more complicated, of course.) There is one function called askForHelp which shows an alert in the new window if a specific value is entered for 'state' and a very simple validateForm which shows an alert on the parent?? window if values are left blank.
The problem is b/c i have all the functions running onClick, and I realize they run concurrently, the new window opens no matter what the user does (with the alerts showing in their various places).
Based on other similar questions here, I tried adding a return false and return true statements to my conditionals, but this hasn't done anything.
Now I know there are much better ways to do what I am doing here, and that my form validation is basic and weak, but as my first foray into programming, it was very important for me to understand everything I am doing, which I do, as of now.
Can anyone show me how to fix this so the new window only opens if the form validates? I would prefer no jquery or no radical chances to the code, if possible.
I appreciate everyone's input. Here is the code:
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="utf-8">
<script type="text/javascript">
function newWindow() {
allInfo= open("", "displayWindow");
allInfo.document.open();
allInfo.document.write('<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body>');
allInfo.document.write(document.getElementById ('state').value);
allInfo.document.write('<p>' + document.getElementById ('zip').value);
allInfo.document.write('</section></body></html>');
allInfo.document.close();
}
function askForHelp () {
var volunteer = document.getElementById('state').value;
if ((volunteer == "New York") || (volunteer == "NY") || (volunteer == "New Jersey") || (volunteer == "NJ")) {
allInfo.alert("test test test");
return false;
}
else {
return true;
}
}
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<script type="text/javascript">
</script>
<form id="infoForm" method="post" name="infoForm">
<p>State: </p>
<p><input type="text" id="state" placeholder="State or Region"></p>
<p>Zip: </p>
<p><input type="text" id="zip" placeholder="Zip code" required /></p>
<p><input type="button" value="Submit Information" onClick="newWindow(), askForHelp(), validateForm()" ></p>
</form>
</body>
</html>
Instead of doing an onClick with newWindow(), askForHelp(), validateForm()
Why not just do one of them (which you want to check first) and then have the function call the others when ready?
function validateForm () {
var x = document.getElementById("state").value;
var y = document.getElementById("zip").value;
if (x == null || x == "" || y == null || y == "") {
alert("Please fill out the required fields.");
return false;
} else {
newWindow(); //Validation was successful so lets open the new window
}
}
This way you can have only validateForm() trigger on click, and the rest will trigger when they need to. You'll need to add askForHelp() inside of the newWindow function to have that trigger when necessary as well.
This is sort of a shameless plug, but I just wrote an open source JS library that attempts to solve problems like this. I call it "Is".
http://jumpkick-studios.github.io/Is/
It uses the Maybe Monad concept:
http://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe
So it would let you solve this problem with more of a Single Responsibility Principle.
var validateState=function(obj){
return (obj.state!=null) //error check here
}
var validateZip=function(obj){
return (obj.zip!=null) //error check here
}
var openWindow=function(){
//do open window stuff
}
var handleError(){
//handle errors here
}
var onClick=function(e){
var form={state:document.getElementById("state").value, zip:document.getElementById("zip").value})
new jumpkick.Is(form)
.is(validateState)
.is(validateZip)
.then(openWindow)
.catch(handleError)
.finally(function(){
//anything else can go here
});
}
ETA: Perhaps an even better way to approach this is to not have a single handle error function, since you may want to display messaging for each wrong field.
So maybe even something like this would work (a little more code though).
var onClick=function(e){
var validInput=true;
var state=document.getElementById("state").value, zip=document.getElementById("zip").value
new jumpkick.Is(state)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for state
});
new jumpkick.Is(zip)
.not().isLongerThan(0)
.then(function(){
validInput=false;
//display message for zip
});
if(validInput) // openWindow
}

Alert if form is empty

How do I check if the whole form is empty and alert it? The form should be able to send even if there's a few empty inputs.
Edit:
Maybe I should've said that it's suppose to be JavaScript or jQuery.
And a better description:
I've got a form with one part that contains 10 input fields, you only have to fill out one.
The other part you only have to fill out name and phone or email but it's 4 fields you could fill with info.
And at last a checkbox making sure the user knows he or she didn't fill out the whole form.
I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.
Here is quick and dirty way using pure JavaScript:
function checkForm​(oForm) {
for (var i = 0; i < oForm.elements.length; i++) {
if (GetElementValue(oForm.elements[i]).length > 0)
return true;
}
alert("all empty");
return false;
}
function GetElementValue(element) {
if ((element.type === "checkbox" || element.type === "radio") && element.checked === false)
return "";
return element.value;
}
​Live test case.
create a validate method like this in JS (extend the Switch for other form Elements like radio or checkbox inputs):
function validateForm(domForm) {
var elements = domForm.elements;
var hasData = false;
var isAEmptyString = function(string) {
if(string) {
return string.length() == 0;
}
return true;
};
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
switch(element.tagName.toLowerCase()) {
case 'textarea':
if(!isAEmptyString(element.innerHTML)) {
return true;
}
break;
case 'input':
if(!isAEmptyString(element.value)) {
return true;
}
break;
case 'select':
if(element.selectedIndex >= 0) {
return true;
}
break;
}
}
return false;
};
you can call it in your form onSubmit handler
<form onsubmit="return validateForm(this);">
<textarea name="a"></textarea>
<input type="text" name="b"></input>
<select name="c">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<input type="submit" />
</form>
I know how to check all fields and alert if one is empty. But what I don't know is how to check if the whole form is empty and alert it.
If that is the case just put a boolean check in your code
var haveAnyErrorsTriggered = false;
// loop through fields and if any are empty change the haveAnyErrorsTriggered to true
// then
if(haveAnyErrorsTriggered){alert("One or more fields are empty.");}
if you want to check if the whole form is empty, just do the opposite
var isAtLeastOneFieldFull = false;
// loop through fields and if any are not empty change the isAtLeastOneFieldFull to true
// then
if(!isAtLeastOneFieldFull){alert("all the fields are empty");}
You are talking about Javascript form validation. Create a Javascript function (called say validateForm) that validates the fields in your form, and pops up an alert if it detects an error. It should return true if the form is to be submitted, and false if there is an error. Then in the your HTML form tag, add the clause onsubmit="return validateForm()", where validateForm is the name of your function.
Maybe the form fields listener example I once cooked in this jsfiddle can help you further? Note that client side validation will never be enough. Anyone can tamper with the javascript in your page, so you allways have to validate a form server side too.

Categories