I have an html form that runs a script to check if the inputs are empty, and if so, it will not submit and it will send an alert. But when the inputs are correct, I want it to go to my contact.php action. It's running the script correctly but its not activating or sending the data to my contact.php. It's running the script correctly but only the script.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="form.js"></script>
<form name="Form" onsubmit="return formValidate(event)" action="contact.php" method="post">
<label>Name:<span id="label_name"></span></label>
<input type="text" id="name" name="name"><br/>
<label >Email:<span id="label_email"></span></label>
<input type="text" id="email" name="email"><br/>
<label >Subject:<span id="label_subject"></span></label>
<input type="text" id="subject" name="subject"><br/>
<label >Email:<span id="label_message"></span></label>
<input type="text" id="message" name="message"><br/>
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
form.js
function formValidate(event) {
event.preventDefault();
var name = document.forms["Form"]["name"].value;
var email = document.forms["Form"]["email"].value;
var subject = document.forms["Form"]["subject"].value;
var message = document.forms["Form"]["message"].value;
if (name == "" || email == "" || subject == "" || message == "") {
output = "*";
alert('Fill out all required inputs');
return false;
} else {
alert('Thanks for contacting me!')
}
return true;
document.getElementById("label_name").innerHTML = output;
document.getElementById("label_email").innerHTML = output;
document.getElementById("label_subject").innerHTML = output;
document.getElementById("label_message").innerHTML = output;
}
Rather than return true/false, use your conditions to decide whether to call event.preventDefault. I don't think it actually matters what you return.
Normally, people write that as the first line because they're going to submit the data in a different way, like AJAX. If you're doing a normal full-page submit, then you don't want to prevent the normal behavior of submitting.
Related
I'm trying to validate a login form but I cannot understand the reason why when I give a wrong input the message from setCustomValidation doesn't show up the first time I click on the submit button (actually input). However when I click on the same button a second time the error message appears as it should. Why is that?
Here's the code.
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\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,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php">
<input id="email" type="text" placeholder="email">
<input id="psw" type="password" placeholder="password">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
Firstly, according to the documentation for setCustomValidity:
You must call the reportValidity method on the same element or nothing will happen.
The reason it works the second time is because when the custom validity message is set, when the "submit" button is clicked again, the browser's built-in form validation takes over and blocks the submit. That is why you do not see the "check validate()" message in the console log on subsequent submits.
Therefore, merely adding something like email.reportValidity() after your email.setCustomValidity is not a solution because on subsequent submits, the submit event handler will not get called, because the form never gets submitted due to the non-null custom validity message. If you try this, you will see that you get the same error message even after filling out the email and password fields. To fix this, you can either add novalidate to the form to bypass the browser validation, or you can clear the custom validity message when the input changes using the input's onchange event.
Here is a working example by adding novalidate to the form and using reportValidity().
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\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,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
email.reportValidity();
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
email.reportValidity();
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
psw.reportValidity();
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
email.reportValidity();
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php" novalidate>
<input id="email" type="text" placeholder="email">
<input id="psw" type="password" placeholder="password">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
Here is a working example using the onchange event on the input fields and using reportValidity(). Notice in this case, the onsubmit handler is only called after the validity message has been cleared and not every time you click the submit button.
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\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,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
email.reportValidity();
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
email.reportValidity();
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
psw.reportValidity();
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
email.reportValidity();
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php">
<input id="email" type="text" placeholder="email" onchange="event.target.setCustomValidity('')">
<input id="psw" type="password" placeholder="password" onchange="event.target.setCustomValidity('')">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
I am creating an application. The HTML file is like the following:
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script type="javascript">
function validateform(){
alert("Hello");
var firstnameErr="";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = "required";
valid = false;
} else if (!fname.value.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script type="javascript">
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When I click on the submit button, it straightaway redirects to "ViewList.php" without seeming to run validatefom(). I added the alert() to check whether the function is executing or not. I want my form to submit only when it meets the validation requirements, not when valid is false.
Besides Typo errors, The main problem that I found is your script is not get executed and your validateform() method is not available. It happened because your script tag type attribute is not correct <script type="javascript">
To make it work you need to change it to this
<script type="text/javascript">
And please change your validation method validateform() as it has too may typo.
What is wrong with the code is that the OP is validating the old-fashioned way with an HTML5 form. Prior to HTML5, you had to use JavaScript for front-end validation; now things are much simpler and easier, too. Of course, the OP would replace the value of the action in the following example with the desired URL.
Note: there were errors in the OP's code, but if you get rid of the JavaScript and code the HTML making sure to add the following to the text input:
required pattern="[a-zA-Z]+"
then the form validates. In other words, you don't have to work so hard when you use HTML5 for form validation :)
<form id="myform" name="myform" method="POST" action="https://www.example.com">
<label for="fname">Firstname</label>: <input name="fname" placeholder="First name" maxlength="20" required pattern="[a-zA-Z]+">
<input type="submit" name="submit" value="Submit">
</form>
For those who prefer to do things the old-fashioned way, see this revision of the OP's code. Note: it uses a minimum of variables, employs short-cuts for less verbosity, and is organized with functions. Also, it is kind to the user's hands, too.
The way you have done you will never be able to use document.write to output anything, use this, working for me:
<!DOCTYPE html>
<script>
function validateform(){
alert("Hello");
var valid = true;
var fname = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (fname==null || fname=="") {
firstnameErr = 'required';
valid = false;
} else if (!fname.match(types)) {
firstnameErr = 'format error';
valid = false;
}
document.getElementById('msg').innerHTML = firstnameErr;
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">* <label id='msg'></label> </span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
It looks you have a series of typo in your code,
try this
<!DOCTYPE html>
<html>
<body style="background-color: #ccc">
<script>
function validateform() {
var firstnameErr = "";
var valid = true;
var name = document.myform.fname.value;
var types = /^[a-zA-Z]+$/;
if (name == null || name == "") {
firstnameErr = "required";
valid = false;
} else if (!name.match(types)) {
firstnameErr = "format error";
valid = false;
}
return valid;
}
</script>
<form name="myform" method="post" onsubmit="return validateform()" action="/Project/ViewList.php">
Firstname : <input type="text" name="fname" placeholder="First name" maxlength="20">
<span class="error">*
<script>
document.write(firstnameErr);
</script>
</span>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
(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;
}
I'm trying to create a simple registration form with basic HTML and PHP to insert data to my database. Basically, I want to validate the fields first before inserting the data and so I have created an external JavaScript file. Problem is, it is displaying the actual JavaScript code on the next page as opposed to validating!
My HTML file:
<html>
<head>
<title>Register Page</title>
<body>
<form id="register" method="POST" action="register.js" onsubmit="return verify()" action="register.php">
Forename: <input type="text" name="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
</body>
</head>
</html>
My JavaScript file:
<script type="text/javascript">
function verify(){
var forename = document.getElementById["forename"].value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
Instead of just validating I'm being redirected to a new webpage showing me the code I have written above.
I am completely new to web development and it would mean a lot if someone could help me out. All I want to do is just validate the fields before adding them to the database.
Two things you have to change
add id to your input control because you are fetching the value of text through Id
<input type="text" name="forename" id="forename">
syntax of getElementById()
var forename = document.getElementById("forename").value;
Once You do the validation for username and password. Submit the form
<script type="text/javascript">
function verify(){
var forename = document.getElementById("forename").value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
<form id="register" method="POST" onsubmit="return verify()" action="register.php">
Forename: <input type="text" id="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
I think you should recheck your syntax for document.getElementById["forename"]
It should be document.getElementById("forename")
You can try debugging step wise. For example, try console.log.
var forename = document.getElementById("forename").value;
console.log(forename);
Try Chrome/Firebox Inspect element > Console and see if anything is been printed.
Hope this helps.
Peace! xD
You shouldn't be declaring register.js as the action for your <form>. The action attribute of a <form> element tells the browser where to send (POST or GET) the form data to, which is why you're being taken to register.js in your browser.
You need to intercept the browser submitting the form, do your validation, and then send the data on to your PHP file (register.php). It might be worth reading some tutorials on javascript form validation, such as this TutorialsPoint one.
What you can be able to do is to take your hole script into a echo in php, then create a php validation for the js and check if js got successfully done then execute script if so.
if you want your javascript on same html page then put this type
<html>
<head>
<title>Register Page</title>
<script type="text/javascript">
function verify(){
var forename = document.getElementById["forename"].value;
if(forename == null || forename == ""){
alert("Forename is empty");
return false;
}
}
</script>
</head>
<body>
<form id="register" method="POST" action="" onsubmit="return verify()" action="register.php">
Forename: <input type="text" name="forename"><br>
Lastname: <input type="text" name="surname"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
</body>
</html>
I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.
HTML:
<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">
<div id="errors"></div>
<label for="author">Name:</label><br/><br/>
<input type="text" name="author" id="message" /><br/><br/>
<label for="author">Message:</label><br/><br/>
<textarea name="message" id="message"></textarea><br/><br/>
<input type="submit" class="button" value="Send Message"/>
</form>
Javascript:
<script type="text/javascript">
function error(message){
return "<p class=\"error\">"+message+"</p>";
}
function validate(){
var form = document.getElementById("contactForm");
var author = document.getElementById("author");
var message = document.getElementById("messsage");
var errors = document.getElementById("errors");
alert(author.value);
if(message.value == '' || author.value == ''){
errors.innerHTML = error("Please fill in all fields.");
return false;
} else {
return true;
}
}
</script>
id=author on your first input element.
Also check out jQuery it will save you time in the long run
You have two elements with the id message and none with author.
The Markup Validator would have picked this up for you.
var message = document.getElementById("messsage");
message has an extra "s".
<input type="text" name="author" id="message" />
You need to change "message" to "author"
This is wrong:
<input type="text" name="author" id="message" />
Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.
Also both your label tags have for="author"; the second one is wrong.
I guess your problem here is too much copy+paste. ;)