Why my form doesn't validate correctly? - javascript

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. ;)

Related

Adding *Required next to an empty input

So I was wondering how I could implement required fields into my code. I tried just using required="" in the <input> tag, however, this doesn't work across all browsers. I was wondering if someone could explain how to add "* Required" next to the input if the user tries to submit and the field is empty.
Here's my form code:
contact.html
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
formvalidate.js
function validateForm()
{
var a=document.forms["Form"]["email"].value;
var b=document.forms["Form"]["subject"].value;
var c=document.forms["Form"]["message"].value;
if (a==null || a=="",b==null || b=="",c==null || c=="")
{
alert("Please Fill All Required Field");
return false;
}
}
var input = document.getElementById('a');
if(input.value.length == 0)
input.value = "Anonymous";
First of all this is wrong:
if (a==null || a=="",b==null || b=="",c==null || c=="")
Presumably you lifted that from here and as noted in the comments, it doesn't do what it claims and will only check the last field.
To add the message you can modify your validation function to check each field and insert some text. The snippet below should give you a basic idea - and since you're new to javascript I've commented each bit with an explanation. Hope this helps:
function validateForm() {
// start fresh, remove all existing warnings
var warnings = document.getElementsByClassName('warning');
while (warnings[0]) {
warnings[0].parentNode.removeChild(warnings[0]);
}
// form is considered valid until we find something wrong
var has_empty_field = false;
// an array of required fields we want to check
var fields = ['email', 'subject', 'message'];
var c = fields.length;
// iterate over each field
for (var i = 0; i < c; i++) {
// check if field value is an empty string
if (document.forms["Form"][fields[i]].value == '') {
// create a div with a 'warning' message and insert it after the field
var inputField = document.forms["Form"][fields[i]];
var newNode = document.createElement('div');
newNode.style = "color:red; margin-bottom: 2px";
newNode.className = "warning";
newNode.innerHTML = fields[i] + ' is required!';
inputField.parentNode.insertBefore(newNode, inputField.nextSibling);
// form is now invalid
has_empty_field = true;
}
}
// do the alert since form is invalid - you might be able to skip this now
if (has_empty_field) {
alert("Please Fill All Required Field");
return false;
}
}
<form class="contact_form" name="Form" onsubmit="return validateForm()" action="contactform.php" method="post">
<label>Name *</label><br/>
<input type="text" name="name" id="noName" placeholder="Full Name"><br/>
<label>Email *</label><br/>
<input type="text" name="email" id="a" placeholder="Email"><br/>
<label>Subject *</label><br/>
<input type="text" name="subject" id="b" placeholder="Subject"><br/>
<label>Message *</label><br/>
<textarea type="text" name="message" id="c" placeholder="Message"></textarea>
<button type="submit" name="submit" class="submit">Submit</button>
</form>
And of course you always need server side validation as well! Client side is really only to help get a snappy UIX and can be easily fail or becircumvented by any user who has a mind to do so. Any data you send to the server needs to be checked over and if something's wrong an error should be returned and handled properly on the form page.
The input field becomes a required field when you specify inside the field that it is a required field. Just placing an asterisk * or placing the word required next to it will not make it required.
Here is how to make an input field required in HTML5
Username *: <input type="text" name="usrname" required>
It is the attribute "required" of the element itself that makes it required.
Secondly.. when using the HTML5 validation you will not need javascript validation because the form will not pass the html5 validation. Having both client-side and server-side is important.

Html Form Unable to Validate Inputs using JavaScript

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>

HTML5 validation executes before custom validation

I have a form which asks user to give some input values. For some initial inputs i am doing custom validation using javascript. At the end of form one field is validated using "html required attribute". But when user clicks on submit button, input box which have required attribute shows message first instead of giving chance to previous ones i.e. not following order of error display. Below i added code and image , instead of showing that name is empty it directly jumps to location input box. This just confuses the end user. Why this problem occurs and how to resolve it?
<html>
<head>
<script>
function validate(){
var name = document.forms['something']['name'].value.replace(/ /g,"");
if(name.length<6){
document.getElementById('message').innerHTML="Enter correct name";
return false;
}
}
</script>
</head>
<body>
<form name="something" action="somewhere" method="post" onsubmit="return validate()">
<div id="message"></div>
Enter Name : <input type="text" name="name" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
</body>
</html>
This is probably just the HTML5 form validation triggered because of the required attribute in the location input.
So one option is to also set the required attribute on the name. And or disable the HTML5 validation with a novalidate attribute. See here for more information: https://stackoverflow.com/a/3094185/2008111
Update
So the simpler way is to add the required attribute also on the name. Just in case someone submits the form before he/she entered anything. Cause HTML5 validation will be triggered before anything else. The other way around this is to remove the required attribute everywhere. So something like this. Now the javascript validation will be triggered as soon as the name input looses focus say onblur.
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
var messageElement = document.getElementById('message');
var string = nameElement.value.replace(/ /g,"");
if(string.length<6){
messageElement.innerHTML="Enter correct name";
} else {
messageElement.innerHTML="";
}
};
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>
Now the above works fine I guess. But imagine you might need that function on multiple places which is kind of the same except of the element to observe and the error message. Of course there can be more like where to display the message etc. This is just to give you an idea how you could set up for more scenarios using the same function:
var nameElement = document.forms['something']['name'];
nameElement.onblur = function(){
validate(nameElement, "Enter correct name");
};
function validate(element, errorMessage) {
var messageElement = document.getElementById('message');
var string = element.value.replace(/ /g,"");
if(string.length < 6){
messageElement.innerHTML= errorMessage;
} else {
messageElement.innerHTML="";
}
}
<form name="something" action="somewhere" method="post">
<div id="message"></div>
Enter Name : <input type="text" name="name" required="required" /> <br/> <br/>
Enter Location : <input type="text" name="location" required="required" /> <br/> <br/><br/> <br/>
<input type="submit" name="submit" />
</form>

Simple HTML form with javascript function

I have an HTML form that I would like to make interact with some JavaScript:
...
<form name="signup">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="email" name="email" id="email" />
<br />
<input type="submit" name="submit" id="submit" value="Signup" onclick="signup()"/>
</form>
...
I have some JavaScript that I want to take the entered email address and store it in an array (it is currently inline with my HTML hence the script tags):
<script type="text/javascript" charset="utf-8">
var emailArray = [];
function signup(){
var email = document.signup.email.value;
emailArray.push(email);
alert('You have now stored your email address');
window.open('http://google.com');
console.log(emailArray[0]);
}
</script>
I was hoping that this simple script would store the email in emailArray but the console remains empty throughout the execution.
What is wrong with this code?
You have two problems.
Your form is named signup and your global function is named signup. The function is overwritten by a reference to the HTML Form Element Node.
Your submit button will submit the form, causing the browser to leave the page as soon as the JS has finished (discarding all the stored data and probably erasing the console log)
Rename the function and add return false; to the end of your event handler function (the code in the onclick attribute.
Please rename your function name (signup) or Form Name (signup),
because when you are try to access document.signup......
It'll make a type error like, object is not a function
Try below Code,
<script type="text/javascript">
var emailArray = [];
function signup() {
var theForm = document.forms['signupForm'];
if (!theForm) {
theForm = document.signupForm;
}
var email = theForm.email.value;
emailArray.push(email);
console.log(emailArray[0]);
}
</script>
<form name="signupForm">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="email" name="email" id="email" />
<br />
<input type="button" name="submit" id="submit" value="Signup" onclick="signup(); return false;"/>
</form>
The problem that is given is that the form name is "signup" and the function is "signup()", then the function is never executed (this is better explained in this answer). If you change your form name or your function name everything should work as expected.
try this code :
<form name="test">
<label id="email" for="email" placeholder="Enter your email...">Email: </label>
<input type="text" name="email" id="email" onBlur=/>
<br />
<input type="button" name="submit" id="submit" value="Signup" onclick="signup()"/>
</form>
<script type="text/javascript" charset="utf-8">
var emailArray = [];
function signup(){
var email = document.getElementById('email').value;
emailArray.push(email);
alert('You have now stored your email address');
window.open('http://google.com');
console.log(emailArray[0]);
return false;
}
</script>
As suggested in the comments, just change your email variable to:
var email = document.getElementById('email').value;
then just push it to your emailArray
EDIT
You'll need to rename the ID of your label. The reason it's currently not working is because the value being returned is that of the first element with the id of email (which is your label, and undefined).
Here's a Fiddle
I would propose two improvements to your code:
Put your javascript right after the <form> element in order to be sure that dom element exist in the document
Attach click handler using addEventListener method. Read more here.
Email:
var emailArray = []; function signup(){ var email = document.getElementById('email').value; emailArray.push(email); alert('You have now stored your email address'); window.open('http://google.com'); console.log(emailArray[0]); return false; } document.getElementById("submit").addEventHandler('click', signup, false);

JQuery: How to check the value of a form field

I have a simple form, with one issue.
In explorer, if nothing is inserted, the placeholder is passed as input of the field.
Here is JSbin: http://jsbin.com/EvohEkO/1/
I would like to make a simple comparision, when form is submitted, to check if the value of the field is equal to "First name", and if yes make the value empty ""
Just this i need.
Someone can help me please?
<form onsubmit="return checkform()">
<input name="test" placeholder="placeholdertext" id="test" />
<input type="submit" value="submitbutton"/>
</form>
in js
you should import jquery latest version this is the link: http://code.jquery.com/jquery-1.10.2.min.js
function checkform(){
var fieldvalue = $.trim($('#test').val());
if(!fieldvalue || fieldvalue=="placeholdertext"){
alert('there is no input');
return false;
}else{
alert('enjoy your form!');
return true;
}
}
This is somewhat easier..
$(document).ready(function(){
$("#form").submit(function(){
$('#form input:text, textarea').each(function() {
if($(this).val()==$(this).attr('placeholder'))
$(this).val(" ");
});
});
});
Just put your field value in hidden type input like this :-
<input id="hdnfield" name="hdnfield" value="<Your Field Value>" />
To check the value of a form field use the val() function on the input element
var input_value = jQuery('Input Element Selector').val();
As I looked to your form, the elements do not have any id attribute, I recommend that you add one to each of them, also change the submit input to button the you have more control on the javascript. so your form will look like :
<form id="form" action="form.php" method="post">
<input id="fname" type="text" placeholder="First name" name="fname"><br>
<label for="fname" id="fnamelabel"></label>
<input id="lname"type="text" placeholder="Last name" name="lname"><br>
<textarea id="message" placeholder="Contact us!" cols="30" rows="5" name="message"></textarea><br>
<br>
<input type="button" value="Submit">
</form>
so your jQuery will look like:
jQuery(document).ready(function(){
jQuery('input[type="button"]').click(function(){
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
var message = jQuery('#message').val();
...... Do whatever you need & then change the input values
...... if all validation has passed the use jQuery('#form').submit(); to submit the form otherwise reset the form:
jQuery('#fname').val("");
jQuery('#lname').val("");
jQuery('#message').val("");
});
});
here is a working version:
jsfiddle working link
You can do it like the following!
<form>
<input type="text" id="first_name" name="first_name"/>
<input type="submit" id="submit" value="submit"/>
</form>
<script type="type/javascript"/>
jQuery.noConflict();
(function ($) {
$(function () {
$("#submit").click(function () {
if ($("#first_name").val() == "first name") {
$(this).val("");
}
});
});
})(jQuery);
</script>

Categories