Validate form input using JavaScript - javascript

I am trying to validate 3 form inputs and based on this I want to display either a success page or a failure page. I must do this using JavaScript. I have this so far:
<script src="scripts/formvalidator.js"></script>
<form method = "post" onsubmit = "validateForm()" >
<label><strong>Name:</strong></label>
<br>
<input type="text" name="name" id="name" placeholder="Enter first and last name" />
<br>
<br>
<label><strong>Email:</strong></label>
<br>
<input type="email" name="usremail" placeholder="hello#wavemedia.ie" />
<br>
<br>
<!-- comment box -->
<legend><strong>Your Message</strong></legend>
<textarea name="comments" id="comments" rows="10" cols="50">
</textarea>
<div id="buttons">
<!-- buttons -->
<input type="submit" name="submit" id="submit" value="Send" style="margin-left:100px;">
<input type="reset" name="reset" id="reset" value="Reset" style="margin-left:20px;">
</div>
</form>
My JavaScript file:
// JavaScript Document
//form validation
function validateForm() {
//name check
var name = document.getElementById("name").value;
var nameLength = name.length; //get length of string stored in name
//email - ref http://www.w3schools.com/js/js_form_validation.asp
var email = document.getElementById("usremail").value;
var atpos = email.indexOf("#"); //gets position of the # symbol in the string
var dotpos = email.lastIndexOf("."); //gets position of the last dot in the string
//message - same method as name validation
var message = document.getElementById("comments").value;
var messageLength = message.length;
if (name.length < 3)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else if (atpos < 1 || dotpos<atpos+2 || dotpos+ 2 >= email.length)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else if (messageLength < 20)
{
alert("Make sure all fields are filled in correctly");
return false;
}
else {
return true;
}
}
The problem is when I run the code and submit the form - no matter what I input - nothing happens.

You have defined a function but I cannot see that you are calling it anywhere. You need to call it by changing the corresponding HTML code to this:
<input type="submit" name="submit" id="submit" value="Send" onclick="validateForm()" style="margin-left:100px;">

First, add onClick="function();" to your code.
If you want to get data by name, use getElementsByName("tagname");
Note that the function returns an array. (Because you can add many inputs with the same name, that's why there's Elements).
Working Fiddle [http://jsfiddle.net/pdp44fx4/2/][1]
I couldn't paste it as a link, sorry.

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.

Javascript not working on submit

In my HTML file, I have the following script:
<script language = "javascript">
function validation(){
var x = document.forms["form"]["fieldx"].value;
var y = document.forms["form"]["fieldy"].value;
var act = document.forms["form"]["action"].value;
if(x == null && y == null && act == "delete"){
var z = confirm("Fields have no input. Proceed at your own risk");
if(z==true) return true;
else return false;
}
}
</script>
And the form:
<form name="form" onsubmit="return validation()" action="cgi-bin/process.cgi" method="GET">
<input type="text" name="fieldx" />
<input type="text" name="fieldy" />
<input type="submit" name="action" value="insert" />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="update" />
</form>
with two input fields named fieldx and fieldy, and a submit type named action which can take any value (i.e. insert, delete and update) as shown above.
Supposedly, when the delete (and only the delete) button is clicked, it will check if there are any inputs inputed on both fields. If there are none, Javascript will prompt and ask the user if it wants to proceed. If he/she clicked yes, well, the process.cgi will be executed and if not, it will just return to the HTML page. However, when I clicked delete, there was no prompt and the cgi was executed.
You have two problems:
First:
x == null && y == null
The values of the fields will never be null. If nothing has been input into them, then their value will be a empty string (i.e. ""). So you need to compare against that and not null.
Second:
document.forms["form"]["action"].value
You have multiple controls named action, so document.forms["form"]["action"] will be a NodeList (which is like an Array). It won't be a single element, and value will always be undefined.
There is no way to tell, from a submit event, which form control was used to activate the form.
Use an onclick handler on the input you care about instead.
<script>
function validation(){
var x = document.forms["form"]["fieldx"].value;
var y = document.forms["form"]["fieldy"].value;
if(x == "" && y == ""){
return confirm("Fields have no input. Proceed at your own risk");
}
}
</script>
and
<input type="submit" name="action" value="delete" onclick="return validation();">
A more modern way to write it would be along these lines:
<form action="cgi-bin/process.cgi">
<input type="text" name="fieldx">
<input type="text" name="fieldy">
<input type="submit" name="action" value="insert" />
<input type="submit" name="action" value="delete" />
<input type="submit" name="action" value="update" />
</form>
<script>
document.querySelector('input[value=delete]').addEventListener('click', validate);
function validate(event) {
var elements = this.form.elements;
if (elements.fieldx.value == "" && elements.fieldy.value == "") {
if (!confirm("Fields have no input. Proceed at your own risk")) {
event.preventDefault();
}
}
}
</script>

PHP Form Submits Before Javascript Validation

I'm having a somewhat common problem of getting my form to validate before submission. I've tried several variations on the same theme and with no dice: at best I could get nothing to submit, but usually my form just ignores codes and submits anyway.
Chances are I'm missing something small but I'd appreciate any help! Essentially just trying to make sure the name isn't empty here (return true; is pointless IIRC but I was getting desperate haha). Once I can get some basic level of validation down it just comes down to coding the JS for more complicated maneuvers so this should be good enough, i hope. Thanks!
<script>
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else {
return true;
}
alert("Bla");
}
</script>
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm(); return false;"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
You're making it to complex.
JavaScript:
function validateForm() {
var x = document.forms["savegameform"]["username"].value;
if (x == null || x == "") {
document.getElementByID("JSError").innerHTML = "Error: Please enter a name.";
return false;
} else { return true; }
}
HTML:
<form name="savegameform" method="post" action="submitsave.php" onSubmit="return validateForm()"><p>
<span class="formline">Name: </span><input type="text" name="username" size="25"><br />
//More of the form
<input type="submit" name="submit" value="Submit">
<span id="JSError">Test.</span>
</p></form>
Your validation works fine, but because you are trying to
document.getElementByID("JSError").innerHTML
instead of
document.getElementById("JSError").innerHTML
JS throws an error and never reaches your "return false".
You can easily see this, when you use your browsers console output. (In firefox and chrome press F12).
Example fiddle: http://jsfiddle.net/6tFcw/
1st solution - using input[type=submit]
<!-- HTML -->
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />
// JavaScript
function validateForm(){
var target = document.getElementById("name"); // for instance
if(target.value.length === 0){
alert("Name is required");
return false;
}
// all right; submit the form
return true;
}
2nd solution - using input[type=button]
<!-- html -->
<input type="button" name="submit" id="submit" value="Submit" />
// JavaScript
window.onload = function(){
var target = document.getElementById("name");
document.getElementById("submit").onclick = function(){
if(target.value.length === 0){
alert("Name is required");
}else{
// all right; submit the form
form.submit();
}
};
};

Form Validation (JavaScript), unsure why it's not working. (No errors, but messagebox doesn't appear)

Basically, I tried to add a form to my website and when the Confirm/Submit button is clicked, the program with check if the Name & e-mail form have to the correct information, otherwise a warning will be displayed.
<script language="javascript" type="text/javascript">
function validateForm()
{
var x=document.forms["form1"]["name"].value;
if (x==null || x=="")
{
alert("Please enter your name");
return false;
}
}
function validateForm()
{
var x=document.forms["form1"]["e-mail"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter your e-mail address");
return false;
}
}
</script>
</head>
<body>
<h2>Form</h2>
<p>Note: Please fill in the following fields below, thank you.</p>
<form id="form1" name="form1" method="post" action="post">
<p>
<label for="name">Name:</label>
<br />
<input type="text" name="name" id="name" />
</p>
<p>
<label for="e-mail">E-mail:</label>
<br />
<input type="text" name="e-mail" id="e-mail" />
</p>
<p>
<label for="msg">Message:</label>
</p>
<p>
<textarea name="msg" id="msg" cols="45" rows="5"></textarea>
</p>
<p>
<input type="button" name="Confirm" id="Confirm" value="Submit" />
</p>
<!-- end .content -->
</form>
</div>
<div class="sidebar2">
<h4> </h4>
<p> </p>
<p><!-- end .sidebar2 --></p>
</div>
<div class="footer"> <img src="pics/copyright.gif" width="960" height="100" alt="footer" /></div>
<!-- end .container --></div>
</body>
</html>
In your code:
> <script language="javascript" type="text/javascript">
The language attribute has been deprecated for about 15 years, the type attribute is no longer required, so:
<script>
> function validateForm () {
> var x=document.forms["form1"]["name"].value;
It is handy to pass a reference to the form from the listener so the function can be more generic. Also, named form controls are added as named properties of the form. If you have a control with a name that is the same as a form property, it will overwrite the form property so you can't access it as a property. Much better to avoid standard property names for element names and IDs, so:
function validateForm(form) {
var x = form.userName.value
then:
> if (x == null || x == "") {
The value of a form control is a string, so x == null will never be true. It's sufficient (and more suitable) to just test:
if (x == "") {
[...]
> function validateForm() {
If you declare multiple functions with the same name, each will overwrite the previous one so you are left with just the last one. You should have a single validation function that does the checks, though each check might be a separate function.
> var x=document.forms["form1"]["e-mail"].value;
> var atpos=x.indexOf("#");
> var dotpos=x.lastIndexOf(".");
> if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
> {
> alert("Please enter your e-mail address");
> return false;
> }
> }
You can use a regular expression to check the format of the e–mail address.
> <form id="form1" name="form1" method="post" action="post">
There generally isn't a need for ID and name attributes on a form, typically just an ID is used. For other form controls, a name is required for them to be successful, there is rarely a need for them to have an ID.
The validation function can be called from the form's submit event, so:
<form id="form1" onsubmit="validateForm(this);" ...>
[...]
> <input type="text" name="name" id="name" />
Don't use XML markup in an HTML document. And don't use element names that are the same as form attribute names as they will make the related form property inaccessible.
</p>
<p>
<label for="e-mail">E-mail:</label>
<br />
Message:
If that is a submit button, then make it type submit. It doesn't need a name or ID if it's value isn't to be submitted:
<input type="submit" value="Submit">
So your form and code can be:
function validateForm(form) {
var reUserName = /\w+/; // User name has some letters
var reEmail = /.+#..+\..+/; // email has some characters, #, then a dot near the end
var passed;
if (!reUserName.test(form.userName.value)) {
passed = false;
// show message for user name
}
if (!reEmail.test(form.eMail.value)) {
passed = false;
// show message for email
}
return passed;
}
Note that the e–mail validation is just what you have, which is not particularly thorough.
Then the form:
<form onsubmit="return validateForm(this);">
Name: <input name="userName"><br>
E-mail: <input name="eMail"><br>
<input type="submit">
</form>
just indent your code and it should be fine, I would love to help, but without seeing the code there's not much i can do. Maybe a link to the page on your site?

Javascript form validation still redirects

For some reason, this code always redirects to education.php regardless of whether or not the fields are blank. I want to verify the fields have values in them, but for some reason they keep redirecting but not writing anything in the database. Any help would be greatly appreciated.
<body>
<form action="education.php" method="post" onsubmit="return validate_fields()">
<div style="text-align: right">
<ul>
First Name: <input id="first_name" name="first_name" size=25/> <br>
Last Name: <input id="last_name" name="last_name" size=25/> <br>
Email: <input id="emailaddress" name="emailaddress" size=25/> <br>
Password: <input id="user_password" name="user_password" type="password" size=25/> <br>
<center><input type="submit" name="submit" id="submit" value="Register Now"/></center>
</ul>
</div>
</form>
<script type="text/javascript">
function validate_fields()
{
var first_name = document.getElementByID("first_name").value;
var last_name = document.getElementById("last_name").value;
alert(""+first_name+" "+last_name);
if (first_name.length < 1 || last_name.length < 1)
{
alert("Please fill in your name.");
return false;
}
var email = document.getElementById("emailaddress").value;
if (email.length < 1)
{
alert("Please fill in your email address.");
return false;
}
var password = document.getElementById("password").value;
if (email.length < 1)
{
alert("Please put in a password.");
return false;
}
alert(first_name+" "+last_name+" "+email);
return false; //was true, changed to see if still redirects.
}
</script>
</body>
You've got a typo on the first line of your function so it isn't returning false (or true), it is just not running at all. This explains both why you don't get any of the alerts and why the form submit goes ahead.
var first_name = document.getElementByID("first_name").value;
// you need a lowercase "d" here ------^
It should be .getElementById(), not .getElementByID().
This is the sort of thing you can easily find for yourself with the appropriate developer tools for your browser. Chrome has this built in (just press ctrl-shift-J to bring up dev tools), or you can add Firebug for FireFox, and IE has had a dev toolbar option for several versions now.
You have a typo here:
var first_name = document.getElementById("first_name").value;
You wrote ByID it sould be ById!

Categories