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>
Related
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.
(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 have done a login page. I want my js validateForm()function to alert a user if they have left out the username or password. This is the code I have got at the moment.
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
if (x==null || x=="")
{
alert("Please enter username");
return false;
}
}
</script>
</head>
<div class="users form">
<br>
<form name="myform" action="Employees/login" onsubmit="return validateForm()" method="post" >
<?php
if (isset($error)) {
echo "<p style='color:red;font-size: 20px''>Username or Password is invalid. Please try again.</p>";
}?>
<p>Enter Username:
<input type="text" name="username" placeholder="username" style="height: 25px;width: 160px;"/></p>
<br><br>
<p>Enter Password:
<input type="password" name="password" placeholder="password" style="height: 25px;width: 160px;"/></p>
<br>
<input type="submit" style="height:35px;width:100px;font-size: 18px; align:center;" value="Sign in">
</form>
</div>
At the moment it is not working, and I think the problem is with the code line "var x=document.forms["myForm"]["username"].value;" Can someone please help?
The issue is forms["myForm"], you used an uppercase F, when actually your form name is all lowercase so it should be:
var x=document.forms["myform"]["username"].value;
// ^ lowercase
Not part of the problem, but you might prefer to use unobtrusive JavaScript to set the onsubmit handler instead of in the HTML attribute:
window.onload = function(){
document.forms["myform"].onsubmit = validateForm;
};
Now, in validateForm you can use this instead of finding the form manually.
function validateForm()
{
var x = this["username"].value;
...
}
I am a beginner and I have written a code for validating the form as:
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
alert("First name must be filled out");
return false;
}}
<!-- html part-->
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><br>
The problem with this code is pressing submit button triggers the validateForm function. How to call the function when the object losses focus?
This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:
<script>
function validate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
y.innerHTML = "Error";
}
}
</script>
The HTML form is:
<form name="myForm">
First name: <input type="text" name="fname" onBlur = "validate()">
<div id = "errorResponse"></div>
<input type="submit" value="Submit">
</form>
The div can be designed in CSS to red color to get user attention and many more tricks can be played.
replace your input element's code by following
<input type="text" onblur="return validateForm();" name="fname">
i guess thats what you are looking for
<html>
<head>
<script type="text/javascript">
function validateForm(oForm){
var els = oForm.elements;
for(var i = 0; i < els.length; i++){
if('string' === typeof(els[i].getAttribute('data-message'))){
return valEl(els[i]);
}
}
}
function valEl(el){
var method = el.getAttribute('data-valMethod');
if('req' === method && (el.value === null || el.value === '')){
alert(el.getAttribute('data-message'));
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="#" onsubmit="return validateForm(this)" method="post">
First name:
<input data-message="First name must be filled out" data-valMethod="req" onchange="return valEl(this)"; name="fname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element.
Since HTML5 the Data-* attributes are very handy for these things :-)
This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.
From here you can expand the valEl-function to accommodate other types of validation.
Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.
Happy coding.
/G
PS http://jsfiddle.net/ePPnn/11/ for sample code
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. ;)