javascript onsubmit event for multiple functions check doesn't work - javascript

In mi validation form I have two input fields in order to write email and confirm it.
Before the submit informations, two confirms are needed:
1-email must seems an email,
2-email one must match the email two.
I can handle these statements each one using two separate javascript functions but i fail when I try to check them all in the onsubmit event attribute. If I write a correct email adress, the form reach the action destination, even if the confirm email doesn't match.
Looking around the web doesn't help me.
Here u are the code (html/javascript):
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Email Validation</title>
<script type="text/javascript">
function isEmail(email, output) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById(email).value;
if (regex.test(email)) {
return true;
} else {
document.getElementById(output).innerHTML = 'wrong email';
return false;
}
}
function compareEmail(email, emailToCompare, output){
var email = document.getElementById(email).value;
var emailToCompare = document.getElementById(emailToCompare).value;
if(emailToCompare == email){
document.getElementById(output).innerHTML = 'ok!';
return true;
}else{
document.getElementById(output).innerHTML = 'emails dont match!';
return false;
}
}
function check(){
return isEmail() && compareEmail();
}
</script>
</head>
<body>
<form action="file.php" method="post" onSubmit="return check()">
<p>Email</p>
<input type="text" name="email" maxlength="50" id="email">
<div id="email_result">
</div>
<br/>
<p>Confirm email</p>
<input type="text" onpaste="return false;" autocomplete="off" name="email" maxlength="50" id="confirm_email" onKeyUp="return compareEmail('email', 'confirm_email', 'confirm_email_result')">
<div id="confirm_email_result">
</div>
<input type="submit" name="submit" value="Register" onclick="return isEmail('email', 'email_result');">
</form>
</body>
The double control doesn't work with the follow script too:
function check(){
if (isEmail() && compareEmail()){
return true;
}else{
return false;
}
}
Nothing changes if I use:
onSubmit="return check()"
or
onSubmit="check()"
in the form event attribute.

You are missing the parameters in the function calls:
function check(){
return isEmail('email', 'email_result') && compareEmail('email', 'confirm_email', 'confirm_email_result');
}
Side note: You have declared variables in the functions with the same name as the parameters. It still works at it is, but the variables are not actually created but will overwrite the parameter values, so the code is a bit confusing.

Related

How I can validate the form with another method like asynchronous methods(promises or async-await)?

How I can validate the form below with another method like asynchronous methods(promises or async-await)?
In the form below, the form is validated if onsubmit ="return validateForm()" is equal to the boolean true and it is not validated if onsubmit ="return validateForm()" is equal to the boolean false.
My problem is : the asynchronous functions always return promises, and don't return boolean value...
<!DOCTYPE html>
<html>
<head>
<title>Hello Javascript</title>
<script type = "text/javascript">
function validateForm() {
var u = document.getElementById("username").value;
var p = document.getElementById("password").value;
if(u== "") {
alert("Please enter your Username");
return false;
}
if(p == "") {
alert("Please enter you Password");
return false;
}
alert("All datas are valid!, send it to the server!")
return true;
}
</script>
</head>
<body>
<h2>Enter your Username and Password</h2>
<div style="border:1px solid #ddd; padding: 5px;">
<form method="POST" action="process-action.html" onsubmit = "return validateForm()">
Username: <input type="text" name="username" id="username"/>
<br><br>
Password: <input type="password" name = "password" id="password"/>
<br><br>
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
The validation code you wrote is synchronous client side code, and you don't need promises to execute it.
What you need to do here is use e.preventDefault because otherwise the submit button will try to trigger a form submit to the server.
Look at this answer as example.
If you take this road, use e.preventDefault to prevent triggering the form submit, validate the form and submit it by launching an ajax call instead.

Can't get input validation Javascript to work

Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.

How to verify the elements of a form in Javascript then Move to a PHP page?

I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}

javascript password checker with confirmation dont work

Could anyone help me i have following issue with it when i put the wrong passwort it still gives no alert and opens the site.(the whole code isnt working and i dont know where the error is..) thank you for your help.
<!DOCTYPE html>
<html>
<head>
<title> passwort </title>
<script type="text/javascript">
function vergleiche(a, b) {
return (a == b) ? true : false;
}
function val(frm) {
if (vergleiche("passwort", frm.password.value){
alert("pw richtig");
}
else {
alert("pw falsch");
frm.password.select();
frm.password.focus;
}
if (frm.password.value == "") {
alert("enter password abla");
frm.password.focus();
return false;
}
if ((frm.password.value).length < 3) {
alert("dein pw sollte schon länger sein hö");
frm.password.focus();
return false;
}
if (frm.confirmpassword.value == "") {
alert("enter password");
return false;
}
if (frm.password.value != frm.confirmpassword.value) {
alert("passwoerter ungleich lan");
}
return true;
}
</script>
</head>
<body>
<h2> passwort validation</h2>
<form name="frm" method="POST" action="pw.php" onSubmit="">
Enter vorname:<input type="text" name="vorname"/>
Enter Password: <input type="password" name="password" placeholder="Enter Password"/><br/>
<br/>
Confirm Password: <input type="password" name="confirmpassword" placeholder="Re-enter Password"/>
<br/>
<input type="submit" value="Submit" onclick=""/>
<input type="reset" value="Reset"/>
</form>
</body>
</html>
As Rax Weber said, you are not even calling your function.
You should not pass your form this way.
I think it's better to do something like this
<input type="submit" value="Submit" onclick="val()" />
And in val function. (Because your form don't have an ID....)
frm = document.getElementsByName("frm")[0];
The line "if(vergleiche("passwort",frm.password.value) {" is incorrect, you are missing one ")"
if(vergleiche("passwort",frm.password.value)) {
Proceeding like this, your function should work. However, I would recommand that you translate your code in english so everyone can understand, and you should also use some IDE like Eclipse or at least Notepad++ to indent your code properly.
Using those tools will make you do less syntax errors.

Validate all form data before submitting

I have created a form in HTML and have use onblur event on each and every field and it is working very fine. The problem is when i click on submit button(which will send data to a servlet) the data is submitted even if it is invalid. Here is an example.
<html>
<head>
<script>
function check()
{
if(checkName()==true)
return true;
else{
alert('vhvh');
return false;
}
}
function checkName()
{
var uname=document.enq.Name.value;
var letters = /^[A-Za-z, ]+$/;
if(uname.match(letters))
{
document.getElementById('Name').style.borderColor = "black";
return true;
}
else
{
document.getElementById('Name').style.borderColor = "red";
//alert('Username must have alphabet characters only');
//uname.focus();
return false;
}
}
</script>
</head>
<body>
<form name="enq" method="post" action="Enquiry" onsubmit="check()">
<input class="textbox" id="Name"style="margin-top:10px;font-size:16px;" type="text" name="Name" placeholder="Full Name" onblur="checkName()" required /><br><br>
<input class="button" type="submit">
</form>
</body>
</html>
How can i resolve this issue?
use
<input class="button" type="button">
and put a onclick event like this:
<input class="button" type="button" onclick="this.submit()">
so you can manipulate data before you subimit it.
There is an "onsubmit" event that allows you to control form submission. Use it to call your validation functions, and only then decide if you want to allow the user to submit the form.
http://www.htmlcodetutorial.com/forms/_FORM_onSubmit.html
You have to use it in the following way if you want it to prevent the form submission:
<form onsubmit="return check()">

Categories

Resources