I am fairly new to coding so forgive me if it is something simple I am missing.
I am trying to validate the First Name field using a simple If statement in the function, but when I test it via live server the form submits without throwing the alert.
function validateForm() {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
return false;
} else {
return true;
}
};
firstNameValid(firstName);
};
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname" onsubmit="return firstNameValid(document.registration.fname)"><br>
</li>
<li>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="lname"><br>
</li>
<li>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
<script>
src = "app.js"
</script>
</body>
</html>
The script should be loaded into the page like this…
<script src="app.js"></script>
…not like this…
<script>
src = "app.js"
</script>
validateForm doesn't return anything - you probably just need to change
firstNameValid(firstName);
to
return firstNameValid(firstName);
But, I'm a little rusty on when a form does / does not end up submitting, you may need to do
function validateForm(e) {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
e.preventDefault();
return false;
} else {
return true;
}
};
return firstNameValid(firstName);
};
<form name="registration" action="page2.html" onsubmit="return validateForm(event)" method="GET">
Related
I need to insert a regular expression to verify the input for URL and email is valid, so where would this go in the code to make it work without messing with anything else? I need to know exactly where it would go and how it would look.
window.onload = function() {
document.getElementById('ifBusiness').style.display = 'none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if (is_business) {
document.getElementById('ifBusiness').style.display = 'block';
document.getElementById('ifResidence').style.display = 'none';
} else {
document.getElementById('ifBusiness').style.display = 'none';
document.getElementById('ifResidence').style.display = 'block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if (address.value == "") {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the bname, tax and url if a business is selected
if (is_business) {
if (bname.value == "") {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
if (tax.value == "") {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if (url.value == "") {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if (rname.value == "") {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if (email.value == "") {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open('', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusb ar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234');
// Set the form target to the name of the newly created popup.
var form = document.querySelector('form[name="myForm"]');
form.setAttribute('target', 'SELU');
return true;
}
head {
text-align: center;
}
body {
text-align: center;
}
.bold {
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h1>Fill the form below</h1>
<!-- center tag is deprecated and should be replaced by CSS -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="text" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
<hr>
<hr>
</body>
</html>
To validate whether or not a user is inputting an url/email, simply change your input type to "url" or "email" and it will be validated for you.
Like so:
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="url" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="email" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
I have my form in Spring MVC into which I need to apply java script validations as well. The code is given below.
function validate_form() {
valid = true;
var fname = document.myform.firstname.value;
if (fname == "") {
document.getElementById('fname_error').innerHTML = "enter the first name";
valid = false;
}
return valid;
}
<html>
<head></head>
<body>
<form:form action="done" method="post" modelAttribute="student" name="myform" onsubmit="return validate_form()">
<p>First name:</p>
<form:input type="text" path="firstname" name="firstname" />
<p id="fname_error"></p>
<input type="submit" value="Sumbit">
</form:form>
</body>
</html>
Here the java script code executes, but the if condition does not executes. Is this problem need to be solved using the controller class? Please help me in this matter.
thank you.
I think you are adding :form there which was not necessary.
Here is the running code:
<html>
<head></head>
<body>
<form action="done" method="post" modelAttribute="student" name="myform" onsubmit="return validate_form()">
<p>First name:</p>
<input type="text" path="firstname" name="firstname" />
<p id="fname_error"></p>
<input type="submit" value="Sumbit" >
</form>
<script type="text/javascript">
function validate_form(){
valid = true;
var fname = document.myform.firstname.value;
if(fname == ""){
document.getElementById('fname_error').innerHTML = "enter the first name";
valid = false;
}
return valid;
}
</script>
</body>
</html>
I'm trying to have a form where I can search a database, but also have simple error handling where I can check if the user did not enter anything and run the function validateForm. However I'm not sure how to do both.
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
Here's the script
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == null) {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
Instead of "null" in if condition simply use empty string like "".
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == "") {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function validateAlphaNumeric()
{
alert("function start");
var alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers="0123456789";
var flag=true;
var prod_id=document.getElementByID("productid").value;
alert(prod_id);
for(var i=0;i<prod_id.length;i++)
{
if(alphabets.indexOf(prod_id.charAt(i))==-1 || numbers.indexOf(prod_id.charAt(i)==-1)
{
alert("value must be alphanumeric");
break;
}
}
var prod_type=document.myform.producttype.value;
for(var i=0;i<prod_type.length;i++)
{
if(alphabets.indexOf(prod_type.charAt(i))==-1 || numbers.indexOf(prod_type.charAt(i)==-1)
{
alert("value must be alphanumeric");
break;
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://localhost:8080/examples/Submit.HTML" method="POST">
<br><br>
Prodcut ID:<input type="text" name="productid" id="productid" size="25" ">
<br><br>
Product Type:<input type="text" name="producttype" id="producttype" size="25" ">
<br><br>
</div>
<input type="submit" onclick="validateAlphaNumeric()" value="Submit">
</form>
</body>
</html>
This is a test page being written to only learn basics.When I am pressing Submit there is no checking happening and it goes to Submit.html page.why? What modification is needed here?
<input type="submit" onclick="validateAlphaNumeric()" value="Submit">
What exactly happens when I am pressing this button?
var prod_id=document.getElementByID("productid").value;
var prod_type=document.myform.producttype.value;
both mechanisms are same ?
This is the Modified one.But still not working. Please help
<!DOCTYPE html>
<html>
<head>
<script>
function validateAlphaNumeric()
{
var alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers="0123456789";
var flag=true;
var prod_id=document.getElementByID("productid").value;
for(var i=0;i<prod_id.length;i++)
{
if(alphabets.indexOf(prod_id.charAt(i))==-1 && numbers.indexOf(prod_id.charAt(i)==-1))
{
alert("value must be alphanumeric");
return false;
}
}
var prod_type=document.myform.producttype.value;
for(var i=0;i<prod_type.length;i++)
{
if(alphabets.indexOf(prod_type.charAt(i))==-1 && numbers.indexOf(prod_type.charAt(i)==-1))
{
alert("value must be alphanumeric");
return false;
}
}
}
</script>
</head>
<body>
<form name="myform" action="http://localhost:8080/examples/Submit.HTML" method="POST">
<br><br>
Prodcut ID:<input type="text" name="productid" id="productid" size="25" ">
<br><br>
Product Type:<input type="text" name="producttype" id="producttype" size="25" ">
<br><br>
</div>
<input type="submit" onclick="validateAlphaNumeric(); " value="Submit">
</form>
</body>
</html>
there you go you forgot closing parenthesis for if statements:
<!DOCTYPE html>
<html>
<head>
<script>
function validateAlphaNumeric()
{
alert("function start");
var alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers="0123456789";
var flag=true;
var prod_id=document.getElementByID("productid").value;
alert(prod_id);
for(var i=0;i<prod_id.length;i++)
{
if(alphabets.indexOf(prod_id.charAt(i))==-1 && numbers.indexOf(prod_id.charAt(i)==-1))
{
alert("value must be alphanumeric");
break;
}
}
var prod_type=document.myform.producttype.value;
for(var i=0;i<prod_type.length;i++)
{
if(alphabets.indexOf(prod_type.charAt(i))==-1 && numbers.indexOf(prod_type.charAt(i)==-1))
{
alert("value must be alphanumeric");
break;
}
}
}
</script>
</head>
<body>
<form name="myform" action="" method="POST">
<br><br>
Prodcut ID:<input type="text" name="productid" id="productid" size="25" ">
<br><br>
Product Type:<input type="text" name="producttype" id="producttype" size="25" ">
<br><br>
</div>
<input type="submit" onclick="validateAlphaNumeric()" value="Submit">
</form>
</body>
</html>
if You want didn't go to Action page You must put return false; at end of onclick like this
onclick="validateAlphaNumeric();return false;"
or put return false; at end of function that you Call with return false; you say browser don't submit
Try returning false when validation fails
I have a login form but I wanna check if the fields are empty then do not submit. I did `return false' on submit but the browser still loads a new page. How can I stop that?
JS:
var username = document.getElementById('usernameField');
var password = document.getElementById('passwordField');
var loginBtn = document.getElementById('loginBtn');
var infoBox = document.getElementById('formInfo');
var isEmpty = /^\s*$/;
var addEventTo = function(id, type, fn, capture) {
if (document.addEventListener) {
id.addEventListener(type, fn, capture);
} else {
id.attachEvent('on'+type, fn);
}
};
function checkIfAllEmpty() {
var loginForm = document.getElementById('loginform'),
allInputs = loginForm.getElementsByTagName('input'),
max = allInputs.length,
i;
for (i = 0; i < max; i++) {
if (allInputs[i].type !== 'submit') {
if (allInputs[i].match(isEmpty)) {
infoBox.innerHTML = 'All your fields are empty';
return false;
}
}
}
}
//addEventTo(loginBtn, 'click', checkIfAllEmpty, false);
if (document.addEventListener) {
loginBtn.addEventListener('submit', checkIfAllEmpty, false);
} else {
loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
}
HTML:
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label><input type="text" placeholder="Enter username" id="usernameField" />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label><input type="password" placeholder="Enter password" id="passwordField" />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
</form>
Many thanks
If it ok to go with html5 (works fine with newer versions of Safari, Chrome, Firefox, Opera > 11.00 but no IE as usual), you can add the required tag in your input field.
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label>
<input type="text" placeholder="Enter username" id="usernameField" required />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label>
<input type="password" placeholder="Enter password" id="passwordField" required />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
Looks like the event listener of the onsubmit are not being added correctly, anyway the easiest way to do it is to add onsubmit="return someValidationFuncThatReturnTrueOrFalse()" in your form:
<form id="loginForm" method="post" action="#" onsubmit="return validate()">
can I ask why you're using this approach on your js code? it could be done much easily if your form is static ...
function validate() {
if (document.getElementById("usernameField").value == "" && document.getElementById("usernameField").value == "") {
alert("all fields are empty");
return false;
} else {
return true;
}
}
or something like that ...
You can use the attribute disabled="disabled" for the form inputs :
http://www.w3schools.com/tags/att_input_disabled.asp
set the submit button as disabled, then add an onchange listener to each input field so that if every field is filled you remove the disable attribute and the user can subit the form.
I use Prototype (as a javascript framework) and this code should work:
js:
function checkEmpties() {
var usr = $('username');
var pass = $('pass');
var frm = $('formId');
if (usr.value && pass.value) {
//frm.submit();
alert('submit');
} else {
alert('failed');
}
}
Event.observe(window, 'DomReady', function() {
var btn = $('submitBtn');
Event.observe('submitBtn', 'click', checkEmpties);
}
html:
<form id="formId">
<input type="text" name="username" id="username" />
<input type="password" name="pass" id="pass" />
<input type="button" id="submitBtn" value="Send" />
</form>
What it does:
Once the document has loaded attaches an event observer to the button, so when it's clicked the function checkEmpties is called.
This function will retrieve the value of the inputs and if they're not empty, submit the form.
Hope it helps