So, I have written this form and this simple javascript to validate the user input.
The thing is, it works perfectly until I add a third function, validateHash, that takes the hashtag inputed into the textbox and checks if it has an hashtag at the beginning.
I sent the code to a friend, and he said that on his PC it works fine (Checks if the fields are filled, and then checks if the hashtag is correct), while on mine it just skips every function and submits the data to the php page without checking anything.
I am using Firefox, and he's using Chrome, but I tried even with the latter with the same results.
Is there something wrong in the code itself?
<!doctype html>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" />
<script language="JavaScript" type="text/javascript">
function validateForm() {
if(validate(document.form.song.value) && validate(document.form.hashtag.value))
if(validateHash(document.form.hashtag.value))
return true;
else
{
alert("Please fill all the fields");
return false;
}
}
function validate(text) {
if(text==null || text=="")
return false;
else
return true;
}
function validateHash(text) {
if(text.charAt(0) != "#") {
alert("Insert hashtag correctly");
return false;
}
else
return true;
}
</script>
<form action="format.php" name="form" method="post" class="basic-grey" onsubmit="return validateForm()">
<h1>Anisongs Form
<span>Fill all the text in the fields</span>
</h1>
<label>
<span>Song lyrics :</span>
<textarea id="song" name="song" placeholder="Max 120 characters" maxlength="120"></textarea>
</label>
<label>
<span>Anime hashtag :</span>
<input id="hashtag" type="text" name="hashtag" placeholder="#loghorizon" maxlength="20"/>
</label>
<span> </span>
<input type="submit" class="button" value="Submit" />
<input type="reset" class="button" value="Cancel" />
</form>
Well, the issues were the brackets. JS really fancies them, and without them even on single lines ifs it wouldn't start to work.
Related
i have a problem with my script, the only problem is outputting error.
the error just bricks after submit_button. so that means when the fields are empty it has to output error and it works but the problem the output just bricks
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post">
<input type="text" id="text_field1" />
<input type="text" id="text_field2">
<button type="submit" id="submit_button">Submit</button>
<button type="submit">Submit</button>
<p id="error_resp"></p>
</form>
<script>
$("#submit_button").click(function() {
if ($("#text_field1").val() == "")
$('#error_resp').text('please fill the required field');
else if ($("#text_field2").val() == "")
$('#error_resp').text('please fill the required field');
else
return true;
});
</script>
There are few issues in your form HTML.
You are not using preventDefault() method which will prevent the default behavior of a form so the inout can be validated.
Also, you do not need check empty input like == "" You can just ! to say if my input is empty then show error message
You are displaying errors in error_resp ideally use .html to clear the previous message and replace with new message
You can read more about .html here
Run snippet to below to see it working.
$("#submit_button").click(function(e) {
e.preventDefault();
if (!$("#text_field1").val()) {
$('#error_resp').html('please fill the first required field');
} else if (!$("#text_field2").val()) {
$('#error_resp').html('please fill the second required field');
} else {
$('#myForm').submit();
console.log('All looking good. Form will submit now')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="myForm" action="filename.php">
<input type="text" id="text_field1" />
<input type="text" id="text_field2">
<button type="submit" id="submit_button">Submit</button>
<p id="error_resp"></p>
</form>
I have been working on this really simple login, where all i want to do is say, if the password is "apple" and password is "123" then link me to another page when i click submit button.
I gave up on the submit button linking portion but i still don't understand why my code won't register, everything looks right to me
<!DOCTYPE html>
<html>
<body>
<form name="loginForm">
<input type="text" name="username" placeholder="Username" value=""/>
<input type="password" name="password" placeholder="Password" value=""/>
<input type="button" name="submit" value="Login" onclick="validate()" />
</form>
<script type="text/javascript">
function validate() {
var user = document.loginForm.username.value;
return user;
var pass = document.loginForm.password.value;
return pass;
if ( (user=="apple") && (pass=="123") ) {
document.write("It worked");
} else {
document.write("Wrong Password");
}
}
</script>
</body>
</html>
Suggestions:
return keyword will exit the function, so the code after return won't be reached. To remove the two 'return' statement is the first step.
document.write will clear the page after document is loaded. You probably need alert function
try using document.getElementById/getElementByName (which is better) instead of document.loginForm...
It is also better to put onsubmit in the form tag (fired after type=submit button is clicked) instead of onclick event for button.
It is better to put Javascript inside the HTML head tag.
Below is a much better/working version:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
var user = document.getElementById("username").value;
var pass = document.getElementById("password").value;
if ( (user=="apple") && (pass=="123") ) {
alert("It worked");
return true;
} else {
alert("Wrong password");
return false;
}
}
</script>
</head>
<body>
<form action="" onsubmit='javascript:return validate()'>
<input type="text" id="username" placeholder="Username" value=""/>
<input type="password" id="password" placeholder="Password" value=""/>
<input type="submit" value="Login" />
</form>
</body>
</html>
I have a website http://www.yaseennikah.com/MyRegister.php. I need to validate the form on the client side. I used javascript code, but it is not working in some mobile browsers. I saw a jquery code here http://jsfiddle.net/WF2J9/16/. But I don't know to add jquery ul. So can any one complete the code please.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>form validation</title>
</head>
<body>
<form action="page1.php" method="post" class="a">
Name : <input type="text" class="text" name="name" id="name" /> <br/>
Address : <input type="text" class="text" name="address" id="address /><br/>
email : <input type="text" class="text" name="email" id="email" /> <br/>
<button id="submit" name="submit">submit</button>
</form>
<script>
$('#submit').on('click', function() {
valid = true;
if (valid && $('#name').val() == '') {
alert ("please enter your name");
valid = false;
}
if (valid && $('#address').val() == '') {
alert ("please enter your address");
valid = false;
}
return valid;
});
</script>
</body>
</html>
You can add jQuery to your web page using their official CDNs Add this to the head of your web page <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
And you can test if jQuery was loaded correctly using this code
if($) {
alert("jQuery loaded");
} else {
alert("jQuery not loaded");
}
Edit:
Here is my version of the validation script (now should be working) and don't forget to remove the trim() function if you don't want it.
Edit 2:
If you want to do this without jQuery, you can use html's automatic form validation example. But this is not supported in ie 9 and earlier.
Or you can try this (Rewritten jQuery code from above to pure js and a second way of form validation).
Validate the form on server's side too !!!
(edit: code updated)
I am running into an error, when trying to clientside-validate with JavaScript that the user has filled in the forms correctly in the Register part of my HTML form.
The HTML and JS file are pretty straightforward:
(Fiddle)
JavaScript and HTML:
function validateForm() {
var name = document.getElementById('username').value;
var email = document.getElementById('email').value;
if (name == null || name == "" || checkIfSpaceOnly(name) == false) {
return false;
}
else if (email == null || email == "" || validateEmail(email) == false){
return false;
}
else
return true;
}
//other methods used in validateForm:
function checkIfSpaceOnly(input) {
var re = /\S/;
return re.test(input);
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
return re.test(email);
}
window.onload = function()
{
var submitBtn = document.getElementById('submit');
submitBtn.addEventListener("click", validateForm);
}
<!DOCTYPE html5>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="design.css">
</head>
<div class = "body1">
<div class = "forms" id="forms">
<h2>Log in</h2>
<form name='loginform' action='login.php' method='POST'>
<input type='email' name='email' placeholder="Email" ><br>
<input type='password' name='password' placeholder="Password" ><br><br>
<input type='submit' value='Log in'><br><br>
</form>
<hr>
<br><h2>Register</h2>
<form onsubmit="" name="register" action="register.php" method="POST" onsubmit="return validateForm()">
<input type="text" name="username" class="form-control" placeholder="Username" id="username"><br>
<input type="email" name="email" class="form-control" placeholder="Email" id="email"/><br>
<input type="password" name="password" class="form-control" placeholder="Passwoord"><br>
<br>
<input type="submit" name="submit" id="submit" value="Create user">
</form>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</html>
So the problem is, it's like the JS file isn't used at all by the HTML file. The form gladly registers any user, no matter if they fulfill the JavaScript file's if conditions or not.
I checked the console, and it says (when the user has been registered), "ReferenceError: validateForm is not defined".
Except checking that the file directories are correct of course, I have searched and read about both general HTML JS form validation Errors, 20-something "similar question" on here, and that specific ReferenceError. I've changed values, names, moved code parts around.... but I can't seem to find the problem and don't know what to do, although it feels like it's just a simple mistake somewhere in the code.
You have 3 problems
Your fiddle is setup incorrectly; all the code is wrapped in an onload which means your validateForm method is not accessible from HTML markup
You have 2 onsubmit attributes in the form - the second contains what it should contain but is being ignored because of the first
You assign the event handler both in markup and in code. Choose one, stick with it.
When you fix these 3 problems, it works as expected and does not submit the form if anything goes wrong (ie, false is returned from validateForm)
https://jsfiddle.net/spwx1rfd/7/
Please check the if condition, you have made a mistake.
Wrong code
if (uName == "") || checkIfSpaceOnly(uName) == false) {
return false;
}
Right code
if (uName == "" || checkIfSpaceOnly(uName) == false) {
return false;
}
The problem i'm having is Im trying to get the contact.php to validate a contact form that is now in the bottom of every page in my site. It worked great with just validating one page and having a hard URL to take them back to. the troubleing code is this.
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['HTTP_REFERER'].$report);
}else{$report='noerror';}
Ive also tryed this:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header($_SERVER['PHP_SELF'].$report);
}else{$report='noerror';}
This is the original code that worked for one page:
/* In case of no valid input go back */
if ($p1==""||$p2==""||$p3==""||$p5==""||$n0!=0||$f0<7||$NL==0||$p7=="") {
header('Location:estimate_page.php?'.$report);
}else{$report='noerror';}
I could just make a new "contact.php" page for every page that has the form in the footer, but thats stupid if i can just make this work. Any ideas
You are thinking in the right direction with javascript/jQuery -- it will allow you to catch the invalid fields before submitting / changing pages. Much better user experience. Only submit when fields are validated.
Here is a link for how to do simple field validation testing with jQuery:
jsFiddle Demo
HTML:
One: <input type="text" id="f1"><br />
Two: <input type="text" id="f2"><br />
Three: <input type="text" id="f3"><br />
Four: <input type="text" id="f4"><br />
<br />
<input type="button" id="mybutt" value="Go" />
javascript/jQuery:
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
}
}); //END mybutt.click
Note that the above example uses jQuery, so you must reference the jQ libraries (usually inside the head tags, something like this:)
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
EDIT:
Here is what the full HTML would look like:
<?php
//Any initial PHP code goes here
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
//javascript
var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
$(document).ready(function() {
$('#mybutt').click(function() {
var errMsg='', badFlds='', firstBad='';
for(var key in arrAll){
chkFld = '#'+arrAll[key];
$(chkFld).removeClass('error');
if ($(chkFld).val() ==''){
$(chkFld).addClass('error');
//alert('Please complete field ' + arrAll[key] );
errMsg += '*' + key + '\n';
if (firstBad=='') firstBad=chkFld;
}
}
if (errMsg != '') {
alert(errMsg);
$(firstBad).focus();
return false;
}
//If it gets to here, it passed validation
$('#yourForm').submit();
}); //END mybutt.click()
}); //END $(document).ready()
</script>
</head>
<body>
<form id="yourForm">
One: <input type="text" id="f1" /><br />
Two: <input type="text" id="f2" /><br />
Three: <input type="text" id="f3" /><br />
Four: <input type="text" id="f4" /><br />
</form>
<input type="button" id="mybutt" value="Click Me">
</body>
</html>
Note that, using the above scenario, no further PHP code would execute until the form is submitted, using the manual $('#yourForm').submit(); statement.