Javascript can't get form to validate - javascript

I'm having problems getting my form to validate with Javascript. I've tried a bunch of different things, but I just can't get it to work. It's possible I'm missing something completely basic, I am pretty new at this. Please let me know what I could possibly change.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<script lang = "text/javascript">
document.getElementById("myForm").onsubmit = validateForm();
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip"))
return true;
else
{
alert(document.getElementById("zip") + " is not a valid zip code");
return false;
}
}
</script>
<form id = "myForm" action = "" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>

The Problem your are, checking the HTML Element not the Value. It should be document.getElementById("zip").value
document.getElementById("myForm").onsubmit = validateForm;
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip").value)){
return true;
}else
{
alert(document.getElementById("zip").value + " is not a valid zip code");
return false;
}
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<form id = "myForm" action="/test" method="get" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
here is a working sample on jsfiddler https://jsfiddle.net/u9suy516/
Optional Information: when using addEventListener you would also have to use the preventDefault() function on the passed event Parameter, but not need the return statments.
function validateForm(event)
{
if (!zipcheck(document.getElementById("zip").value)) {
alert(document.getElementById("zip").value + " is not a valid zip code");
event.preventDefault();
}
}

Related

How to use the onsumit function to call the output inside login function?

I am new to javascript. I am working on a login form with CryptoJS. I have three functions in total. They are onsubmit function, checkLogin function and encrytion function. I have to use the onsubmit function to call the checkLogin function to validate user input but I don't know how to do so. Besides, I have to use the encrytion function to turn user input to another string, then use the checkLogin function to call the encryption function and get the string. The checkLogin function and encryption function should not directly access DOM. Finally both functions will be used for Jasmine testing but I don't need to do it right now. I just want to make my form works normally. I don't know how to exactly modify my onsubmit function and checkLogin function to make it works.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Login Page</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
<script src="Jasmine/lib/md5.js"></script>
</head>
<body>
<header>
<h1>Login Page</h1>
</header>
<section id="form" class="form">
<form name="submitForm" action="#" method="POST">
<fieldset class="form__field">
<legend>User Authentication</legend>
<p><label for="in_username" class="form__username" >Username:</label>
<input type="text" name="username" id="in_username"/></p>
<p><label for="in_password" class="form__password">Password:</label>
<input type="password" name="password" id="in_password"/></p>
<input type="submit" value="Log in" class="form__submit" />
</fieldset>
</form>
</section>
<!-- output message -->
<section id="output" class="output">
</section>
</body>
</html>
Encryption function is confirmed to be ok.
function md5Encrypt(stringIn) {
"use strict";
var md5string = new CryptoJS.MD5(stringIn);
return md5string.toString();
}
What I want to do is to output the result in the same page and this is my current code.
How to use checkLogin function to call encryption function and return true when username is abc and password is 123123? After I output a variable, how do I use the onsubmit function to take the variable? Thank you!
window.onload = function () {
"use strict";
var myLogin = document.forms.submitForm;
var myMessage = document.getElementById("output");
myMessage.classList.add("displaynone");
myLogin.onsubmit = processForm;
function processForm() {
var inName = document.getElementById("in_username");
var inPassword = document.getElementById("in_password");
checkLogin(inName, inPassword);
myMessage.classList.add("displayblock");
myMessage.innerHTML = output;
return false;
}
function checkLogin(inName, inPassword){
var myName = "abc";
var myPassword = "123123";
var output = "";
var noName = "No username entered";
var noPassword = "No password entered"
var valid = "Welcome back!";
var invalid = "Invalid Username or Password";
if(inName.value(myName) && inPassword.value(myPassword)){
output = valid;
} else if (inName.value("")){
output = noName;
} else if(inPassword.value("")){
output = noPassword;
} else {
output = invalid;
}
return output;
}
};

HTML/JS code to display Error Message if Input is Wrong

I am trying to write an HTML5 - JS Program that displays an Error Message IF the User Input is Empty. But I am not able to get the "Error Message", even thou I can't seem to find any issues.
I am a complete beginner and the Video Tutorial I am using doesn't have any User Support.
Please Help.
I have tried all I know but no avail.
<!DOCTYPE html>
<html>
<head>
<title>Error Message Display</title>
<script type="text/javascript">
function displayInput()
{
var testInput = document.getElementById("name").value;
if (testInput.lenght == 0)
{
document.getElementById("para").innerHTML = "NOOOO";
}else
document.getElementById("para").innerHTML = testInput;
}
</script>
</head>
<body>
<input id="name" type="text"/>
<button onclick="displayInput();">Show The Text</button>
<p6 id="para"></p6>
</body>
</html>
If the Input is Empty an Error Message i.e NOOOO should display.
hi you made spelling mistake in length property of element
it should not be lenght
function displayInput()
{
let el = document.getElementById("name");
let para = document.getElementById("para")
var testInput = el.value;
if (testInput.length == 0)
{
para.innerHTML = "NOOOO";
}
else{
para.innerHTML = testInput;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Error Message Display</title>
</head>
<body>
<input id="name" type="text"/>
<button onclick="displayInput();">Show The Text</button>
<p6 id="para"></p6>

How to get the value of a checkbox using getelementbyID inside a form

I have a code which worked fine while I was testing it now I decided it to include it inside a form and it just does not want to work. If I remove the form tag it works and with the form tag it does not.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script>
function action() {
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage['username'] = document.getElementById('username').value;
window.localStorage['password'] = document.getElementById('password').value;
window.localStorage['unpwchecked'] = "yes";
alert("Saved!");
}
else
{
window.localStorage['username'] = "";
window.localStorage['password'] = "";
window.localStorage['unpwchecked'] = "";
}
}
function action2() {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
}
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button onclick="action()" type="button">Save values!</button></p>
<p><button onclick="action2()" type="button">Load values!</button></p>
</form>
<script>
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage['username'];
document.getElementById('password').value = window.localStorage['password'];
document.getElementById("UPCheck").checked = true;
}
</script>
</body>
</html>
Remove the form tag and values are properly saved in localstorage.
The problem comes from the function name. If you rename
function action()
to
function action1()
and also modify
<button onclick="action1()" type="button">Save values!</button>
then your code will work.
I notices that without the form tag, the code works ok. If you add the form element, then you will get a console error, stating that action() is not a function. I'm just guessing that there is a conflict between the function name action() and the form attribute action
Try:
var isChecked = document.getElementById("UPCheck").checked;
Probably better practice to add an event handler for the buttons, that works with the form tags. Kind of interesting that it works with renaming the function.
JS
document.getElementById("save").addEventListener("click", function(){
var checkBox = document.getElementById("UPCheck");
if (checkBox.checked == true){
window.localStorage.username = document.getElementById('username').value;
window.localStorage.password = document.getElementById('password').value;
window.localStorage.unpwchecked = "yes";
alert("Saved!");
}
else
{
window.localStorage.username = "";
window.localStorage.password = "";
window.localStorage.unpwchecked = "";
}
});
document.getElementById("load").addEventListener("click", function(){
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
});
var alerted = localStorage.getItem('unpwchecked');
if (alerted == 'yes') {
document.getElementById('username').value = window.localStorage.username;
document.getElementById('password').value = window.localStorage.password;
document.getElementById("UPCheck").checked = true;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<form>
<input type="text" id="username" name="username" value="">
<input type="text" id="password" name="password" value="">
Save username / password in cookies: <input type="checkbox" id="UPCheck" name="savelocalunpw">
<p><button id = "save" type="button">Save values!</button></p>
<p><button id = "load" type="button">Load values!</button></p>
</form>
</body>
</html>
You can use "dot" notation for localStorage.

Even after validation failed the new page is redirected

I am implementing a simple code just to figure out why validation is not working in my browser.
But validation is not working. Idk y.
It is just redirecting to next page
newjsp.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function validation()
{
var a=document.form1.txt1.value;
if(a=="")
{
alert("Hey");
return false;
}
return true;
}
</script>
</head>
<body>
<form id="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
<input type="text" id="txt1">
<input type="submit" id="sub">
</form>
</body>
Use opposite logic - something must be OK, then turn TRUE, in all other cases, return FALSE.
function validation()
{
var a = document.getElementById('txt1').value;
if (typeof a != "undefined" && a != "")
{
// `a` is in very good condition :)
return true;
}
alert('hey');
return false;
}
I think, your document.form1.txt1.value is not filled correctly, so your value a is probably undefined and not "", so it will return TRUE.
Try to debug with console.log(a);
And finally, use var a = document.getElementById('txt1').value;, just in case :)
instead of form id use name
<script>
function validation()
{
var a=document.form1.txt1.value;
console.log(a);
if(a=='')
{
alert("Hey");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
<input type="text" id="txt1">
<input type="submit" id="sub">
</form>
</body>
Update
Do not use this as a function parameter. this is a keyword. Use any other variable. Something like this
function validation(form) {
var a=form.txt1.value;
if(a==="") {
window.alert("Hey");
return false;
}
return true;
}
When the form is like this
<form name="form1" onsubmit="return validation(this)" action="newjsp1.jsp">
....
</form>
Try document.forms.form1.txt1.value;
function validation(){
var a=document.forms.form1.txt1.value;
if(a==""){
alert("Hey");
return false;
}
return true;
}
Check the demo http://jsbin.com/vuxoha/1/edit

Print value using GET or POST

My goal is to print the value entered in the Firstpage.html to basicform.html using GET or POST.
I need it to be done only using Html and JavaScript or Ajax.
Code for Firstpage.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function result()
{
var x=document.forms["fom"]["name"].value;
$_GET[0]=x;
}
</script>
</head>
<body>
<form method="get" action="basicform.html" name="fom">
Your name: <input type="text" id="name" name="name" size="25" /> <br />
<input type="submit" value="submit" onclick="result()" />
</form>
</body>
</html>
This is the code in basicform.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script>
function loaad()
{
var name = $_GET[x];
if(isset($_get(submit)))
{
document.write(name);
}
}
</script>
<body onload="loaad();">
</body>
</html>
You can only get the GET parameters using JavaScript. If JavaScript was able to access post variables, it would create security risks.
This is how you would get the GET parameters using JS.
var $_GET = {}, args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}
I Completed the Task Successfully using localStorage.
Code for Firstpage.html
<script>
function store()
{
if(localStorage)
{
document.getElementById("contactForm").addEventListener("submit",
function()
{
var name = document.getElementById("name").value;
localStorage.setItem('name',name);
var age = document.getElementById("age").value;
localStorage.setItem('age',age);
})
}
}
</script>
</head>
<body>
<form id="contactForm" action="result.html" method="POST" >
<label for="name">Name</label>
<input type="text" name="name" id="name">
<label for="Age">Age</label>
<input type="text" name="age" id="age">
<input type="submit" value="send" onclick="store()">
</form>
</body>
and the result.html is
<script>
window.onload= function()
{
var x =localStorage.getItem('name');
var y=localStorage.getItem('age');
if((x !="undefined") || (x!="NULL"))
{
document.getElementById("ret").innerHTML="hello "+x+" your are "+y+" years old";
}
}
</script>
</head>
<body>
<div id="ret" style="position:absolute; left:400px; top:200px; height:400px; width:400px; text-align:center">
Result
</div>
</body>
If you want to get GET parameter from Javascript use this function :
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
Reference:
Get url parameter jquery Or How to Get Query String Values In js
Then simply use this:
var name = getUrlParameter('x');
//assuming url: http://yoursite.copm/?x=test
document.write(name);
Your form is sending the data using get (different than PHP's $_GET). This means that the values sent will appear in the address of the web page the form is sent to - no need for JS on this page. For example, on submitting your firstpage.html form you may get to:
basicform.html?name=Bob
This works well since JavaScript can get those parameters (not very cleanly, but it can). Put this on basicform.html:
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var query = getQueryParams(document.location.search);
Then, you'll use the query variable to print out the name value.
document.write(query.name);
getQueryParams function from here on SO.
Also, the reason using $_GET didn't cause errors is that it's formed like any other valid JavaScript variable name. However, it's just that - the same as any JS variable - and has no relation to PHP's $_GET variable.

Categories

Resources