Clearing input value onclick - javascript

I'm looking for some help on clearing the values of my input and text areas onclick after I insert an error message into the value of my inputs and textarea. Here's my code:
HTML
<form name="form" action="contact-handler.php" method="post" onsubmit="return contact();">
<input type="text" name="name" placeholder="Name:">
<input type="text" name="email" placeholder="E-mail:">
<select name="subject">
<option value="0">Categories</option>
<option value="1">Web Design</option>
<option value="2">Web Development</option>
<option value="3">Graphic Design</option>
<option value="4">Photography / Video</option>
<option value="5">Marketing</option>
</select>
<textarea name="message" placeholder="Message:"></textarea>
<input class="button" type="submit" value="Send">
</form>
JavaSript
function contact() {
var name = form.name.value;
var email = form.email.value;
var atPosition = email.indexOf("#");
var dotPosition = email.lastIndexOf(".");
var subject = form.subject.value;
var message = form.message.value;
var flag = 0;
// Name
if(name != "" && name.length > 2 && !/[\d]/.test(name)) {
flag++;
form.name.style.border="1px solid #CCC";
}
else{
form.name.style.border="1px solid #D73300";
form.name.value="Please enter a valid name";
}
// Email
if(email != "" && atPosition > 1 && dotPosition > atPosition + 2 && dotPosition + 2 <= email.length) {
flag++;
form.email.style.border="1px solid #CCC";
}
else{
form.email.style.border="1px solid #D73300";
form.email.value="Please enter a valid email";
}
// Subject
if(subject > 0) {
flag++;
form.subject.style.border="1px solid #CCC";
}
else{
form.subject.style.border="1px solid #D73300";
}
// Message
if(message != "" && message.length > 30) {
flag++;
form.message.style.border="1px solid #CCC";
}
else{
form.message.style.border="1px solid #D73300";
form.message.value="Please enter a valid message";
}
// Flag
if(flag == 4) {
return true;
}
else
{
return false;
}
}

Change the value of the placeholder attribute, not the input value. And use classes for styling:
form.element.className = 'error';
form.element.setAttribute('placeholder', "Can I haz a value?");
(fiddle)
A nicer way would be to add the required="required" attribute to your form elements, then you can just style them using the :invalid pseudo-class:
input:invalid, textarea:invalid{
border: ....
}

Vanilla JS way:
window.onload = function() {
var form = document.forms["form"];
var formElems = form.getElementsByTagName('input');
formElems.concat(form.getElementsByTagName('textarea'));
for(i=0; i<formElems.length; i++) {
formElems[i].onclick = function() {
if(this.style.borderColor == '#CCC') {
this.value = '';
}
}
}
};
put this above your contact function.

Related

Dynamic search form using jquery

I am trying to create a search form using jquery for following tasks to do:
A user can upload file or input text into the text area or select option from the drop-down menu but these options will appear based on the selection of 1st drop-down menu.
The user can clone this form number of times but not more than max options of the 1st drop-down menu.
The user can remove form < max options from the 1st drop-down menu.
But problems are:
Task 1 is working only on the original form but not in cloned one.I think due to the tag id, it only does the task for original one, so how can I do that for multiple occasion?
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
$('#alarm_action').change(function (e) {
if ($("#alarm_action").val() == "listofcompany") {
$('#filefield').show();
$("#myTextarea").hide();
$("#showForProg").hide();
} else if ($("#alarm_action").val() == "runprogram") {
$('#filefield').hide();
$("#myTextarea").hide();
$("#showForProg").show();
} else {
$('#filefield').hide();
$("#myTextarea").show();
$("#showForProg").hide();
}
});
$(addButton).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-field">\
<select class="removeDuplication" name="searchtype" id="alarm_action" required>\
<option value="cityname">City Name</option>\
<option value="listofcompany">Company</option>\
<option value="runprogram">Run Program</option></select>\
<body onload="setProg();">\
<select name="searchtermorg" id="showForProg" style="display: none;"></select>\
</body>\
<input id="filefield" type="file" name="foofile" style="display: none;"/>\
<textarea id="myTextarea" name="something" ></textarea>\
Remove\
</div>'); //add input box
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change','select.removeDuplication',function(e) {
e.preventDefault();
var cI = $(this);
var others=$('select.removeDuplication').not(cI);
$.each(others,function(){
if($(cI).val()==$(this).val() && $(cI).val()!="") {
$(cI).val('');
alert($(this).find('option:selected').text()+' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall=true;
var fillupfield=true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type !=""){
if (query.type == "listofcompany") {
query.value =$(field).find('#filefield').val();
} else if (query.type == "runprogram") {
query.value =$(field).find('#showForProg').val();
} else {
query.value =$(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else{
slectedall=false;
}
});
var url = window.location.href;
url+="/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() ===""){
fillupfield=false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall===false){
alert('Please select option.');
} else {
if (fillupfield===false){
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
var progarray = ['Python','Java','R'];
function setProg() {
var newOptions=progarray;
var newValues=progarray;
selectField = document.getElementById("showForProg");
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++)
{
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
<div class="form-field">
<select class="removeDuplication" name='searchtype' id="alarm_action" required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body onload="setProg();">
<select name="searchtermorg" id="showForProg" style="display: none;"></select>
</body>
<input id="filefield" type="file" name="foofile" style="display: none;"/>
<textarea id="myTextarea" name="something"></textarea>
</div>
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Can anybody help me to fix these problems? thank you
Issues with our current code:
In a valid HTML, idof an element should be unique. But here you are repeating the element id every time you clone the elements. Use class instead of id.
Use $.on to bind events to elements which are added dynamically (eg, the dropdown change event)
Spaghetti code which is not maintainable - I've tried cleaning up a bit. But there is a lot of scope for clean up.
I've fixed the issue which you have mentioned by fixing the above-mentioned points. But as I said, there is a lot of clean-up to be done before this could be used in a project.
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var addButton = $("#form-add"); //Add button ID
var form = $('#main-form');
var x = 1; //initlal text box count
var progarray = ['Python', 'Java', 'R'];
wrapper.append($("#content-template").html());
//alert($(".showForProg").length);
setProg($(".showForProg"));
$(document).on('change', '.alarm_action', function(e) {
var $container = $(this).parents('.form-field');
if ($(this).val() == "listofcompany") {
$('.filefield', $container).show();
$(".myTextarea", $container).hide();
$(".showForProg", $container).hide();
} else if ($(this).val() == "runprogram") {
$('.filefield', $container).hide();
$(".myTextarea", $container).hide();
$(".showForProg", $container).show();
} else {
$('.filefield', $container).hide();
$(".myTextarea", $container).show();
$(".showForProg", $container).hide();
}
});
$(addButton).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
wrapper.append($("#content-template").html());
setProg($(".showForProg").last());
} else {
alert("Sorry, you have reached maximum add options.");
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(document).on('change', 'select.removeDuplication', function(e) {
e.preventDefault();
var cI = $(this);
var others = $('select.removeDuplication').not(cI);
$.each(others, function() {
if ($(cI).val() == $(this).val() && $(cI).val() != "") {
$(cI).val('');
alert($(this).find('option:selected').text() + ' already selected.');
}
});
});
form.on('submit', function(e) {
e.preventDefault()
var queries = [];
var slectedall = true;
var fillupfield = true;
form.find('.form-field').each(function(index, field) {
var query = {};
query.type = $(field).find('select').val();
console.log(query.type);
if (query.type != "") {
if (query.type == "listofcompany") {
query.value = $(field).find(',filefield').val();
} else if (query.type == "runprogram") {
query.value = $(field).find(',showForProg').val();
} else {
query.value = $(field).find('textarea').val().replace(/\n/g, '\\n');
}
queries.push(query);
} else {
slectedall = false;
}
});
var url = window.location.href;
url += "/search/advanced/";
for (i = 0; i < queries.length; i += 1) {
var query = queries[i];
var ampOrQ = (i === 0) ? "?" : "&";
if (query.value.trim() === "") {
fillupfield = false;
} else {
url += ampOrQ + query.type + "=" + query.value;
}
};
if (slectedall === false) {
alert('Please select option.');
} else {
if (fillupfield === false) {
alert('Input can not be left blank');
} else {
//alert(url);
window.location.href = url;
}
}
});
function setProg($programDropdown) {
$.each(progarray , function(key, value) {
$programDropdown
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="main-form" class="navbar-form" action="" method="get" enctype='multipart/form-data'>
<div class="input_fields_wrap">
</div>
<input class="btn btn-secondary" type="button" value="Add" id="form-add">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
<script type="text/template" id="content-template">
<div class="repeat-container">
<div class="form-field">
<select class="alarm_action removeDuplication" name='searchtype' required>
<option value="cityname">City Name</option>
<option value="listofcompany">Company</option>
<option value="runprogram">Run Program</option></select>
<body>
<select name="searchtermorg" class="showForProg" style="display: none;"></select>
</body>
<input class="filefield" type="file" name="foofile" style="display: none;" />
<textarea class="myTextarea" name="something"></textarea>
</div>
</div>
</script>

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

Js validate multipe input fields with same name

Ok i have multy fields with same name, and i want to check is all fields are not empty. My code works if i have only one input, but i have no idea how to do that with more inputs
<input class = "new_input" type=text name="name[]"/>
<input class = "new_input" type=text name="name[]"/>
function validation(){
var x = document.forms["form"]["name"].value;
if(x ==='')
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
return false;
}
else
{
return true;
}
}
for example if enter only one field, validation will work, and i want to check all fields
Using just JS you could do something like
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<input class="new_input" type="text" name="name[]">
<button onclick="validate()">Validate</button>
<script type="text/javascript">
function validate() {
var inputs = document.getElementsByTagName("input");
var empty_inputs = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.indexOf('name') == 0) { // check all inputs with 'name' in their name
if (inputs[i].value == '') {
empty_inputs++;
console.log('Input ' + i + ' is empty!');
}
}
}
if (empty_inputs == 0) {
console.log('All inputs have a value');
}
}
</script>
You have tagged jquery, so I have given something which works in jquery
http://jsfiddle.net/8uwo6fjz/1/
$("#validate").click(function(){
var x = $("input[name='name[]']")
$(x).each(function(key,val){
if($(val).val().length<=0)
{
$("#warning").html("Morate uneti vrednost!").css('color','red');
}
});
});
Try this:
function validate(){
var error = 0;
$.each( $("input[name='name[]']"), function(index,value){
if( value.value.length == 0){
$("#warning").html("Morate uneti vrednost!").css('color','red');
error = 1;
return;
}
});
if(!error){
$("#warning").html("");
}
}
Check it out here: jsFiddle

error inner HTML on the wrong place

I have a form validation on 3 required input fields: name, address and city.
I made this javascript:
function Validate(form) {
var error_name = "";
var error_address = "";
var error_city = "";
if (form.name.value.length == 0) {
form.name.style.border = "1px solid red"; /*optioneel */
form.name.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_name = "Name cannot be left blank!";
}
if (form.address.value.length == 0) {
form.address.style.border = "1px solid red"; /*optioneel */
form.address.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_address = "Address cannot be left blank!";
}
if (form.city.value.length == 0) {
form.city.style.border = "1px solid red"; /*optioneel */
form.city.style.backgroundColor = "#FFCCCC"; /* optioneel */
error_city = "City cannot be left blank!";
}
if (error_name.length > 0) {
document.getElementById("error_name").innerHTML = error_name ;
return false;
}
if (error_address.length > 0) {
document.getElementById("error_name").innerHTML = error_address ;
return false;
}
if (error_city.length > 0) {
document.getElementById("error_name").innerHTML = error_city ;
return false;
}
return true;
}
document.getElementById("aanmelden").onsubmit = function () {
return Validate(this);
};
And this is a piece of the form:
<div id="form" >
<h3>Aanmelding WIES Congres</h3>
<p class="legend">Deelnemer</p>
<fieldset class="input2" id="Deelnemer">
<label>Naam:</label>
<div id="error_name"></div>
<input type="text" name="name" maxlength="25" size="25">
<label class="right">Bedrijf:</label>
<input class="right" type="text" name="company" maxlength="25" size="25">
<br/>
<label>Adres:</label>
<div id="error_address"></div>
<input type="text" name="address" maxlength="25" size="25"> <br />
<label>Postcode:</label>
<input type="text" name="postalcode" maxlength="6" size="6"> <br />
<label class="right">Plaats:</label>
<div id="error_city"></div>
<input class="right" type="text" name="city" maxlength="25" size="25">
<label>Land</label>
<select name="country">
and so on----
As you can see in the form, the name error should occur above the name field, the address error above the address field and so on..
But this is not happening: all errors are shown above the name field, wether it is name, address or city error...
What do i do wrong?
It looks like all of your errors are targeting the same div : #error_name.
Try changing each one to target the appropriate div:
document.getElementById("error_name").innerHTML = error_name;
document.getElementById("error_address").innerHTML = error_address;
document.getElementById("error_city").innerHTML = error_city;
Also, some of your input names do not match their references. For example:
form.name should be form.form_name
form.address should be form.form_address
form.city should be form.form_city
In order to display all the errors at once (instead of just one per form submission) you'll need to remove all the return false; lines and put one conditional return at the end of the function. Also, you'll need a way to "clear" the errors after the user corrects blank inputs.
Here is the restructured function:
function Validate(form) {
// INITIALIZE VARIABLES
var error_name = "";
var error_address = "";
var error_city = "";
var valid = true;
// CHECK FOR BLANK INPUTS, SET ERROR MESSAGES
if (form.form_name.value.length == 0) {
error_name += "Name cannot be left blank!";
}
if (form.form_address.value.length == 0) {
error_address += "Address cannot be left blank!";
}
if (form.form_city.value.length == 0) {
error_city += "City cannot be left blank!";
}
// UPDATE ERROR MESSAGE DISPLAYS
document.getElementById("error_name").innerHTML = error_name;
document.getElementById("error_address").innerHTML = error_address;
document.getElementById("error_city").innerHTML = error_city;
// IF ERROR MESSAGE EXISTS, CHANGE STYLES AND SET VALID TO FALSE
// ELSE IF NO ERRORS, RESET STYLES
if (error_name.length > 0) {
form.form_name.style.border = "1px solid red";
form.form_name.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_name.style.border = "none";
form.form_name.style.backgroundColor = "#FFFFFF";
}
if (error_address.length > 0) {
form.form_address.style.border = "1px solid red";
form.form_address.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_address.style.border = "none";
form.form_address.style.backgroundColor = "#FFFFFF";
}
if (error_city.length > 0) {
form.form_city.style.border = "1px solid red";
form.form_city.style.backgroundColor = "#FFCCCC";
valid = false;
} else {
form.form_city.style.border = "none";
form.form_city.style.backgroundColor = "#FFFFFF";
}
// RETURN FORM VALIDITY (TRUE OR FALSE)
// "FALSE" STOPS THE FORM FROM SUBMITTING
return valid;
}
// CONFIGURE ONSUBMIT FUNCTION
document.getElementById("aanmelden").onsubmit = function () {
return Validate(this);
};
Here is a working example (jsfiddle).

Form Validation with Javascript using window.onload

Hi there I am really stuck on this and since I am a javscript beginner this boggles my mind.
Is there someone who knows how to write the following javascript form validation?
I am sure that it is very simple, but I can not figure this one out to save my life.
Thank you for you sharing your knowledge.
I need to write WITHOUT jquery the following form validation. Whenever an error is encountered, prevent the form from being submitted. I need to use the window.onload function to assign a validation callback function. There are 4 inputs which get validated by the javascript code. Also the javascript needs to be in its own file.
Validation Rules are as follow:
INPUT: Username; Required (yes); Validation (Must be 5-10 characters long).
INPUT: Email; Required (yes); Validation (Must have an # sign, must have a period).
INPUT: Street name; Required (no); Validation (Must start with a number).
INPUT: Year of birth; Required (yes); Validation (must be numeric).
My code looks as follow:
HTML:
<!DOCTYPE html>
<html>
<head>
<script defer="defer" type="text/javascript" src="form.js"></script>
</head>
<body>
<form action="fake.php">
Username*: <input type="text" class="required" name="u"/><br/>
Email*: <input type="text" class="required" name="p"/><br/>
Street address: <input type="text" class="numeric" name="s"/><br/>
Year of birth*: <input type="text" class="required numeric" name="b"/><br/>
<input type="submit"/><br/>
</form>
</body>
</html>
JS
document.forms[0].elements[0].focus();
document.forms[0].onsubmit=function(){
for(var i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if((el.className.indexOf("required") != -1) &&
(el.value == "")){
alert("missing required field");
el.focus();
el.style.backgroundColor="yellow";
return false;
}
if((el.className.indexOf("numeric") != -1) &&
(isNaN(el.value))){
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor="pink";
return false;
}
}
}
without changing much of your code ... updated your code for other validation like length (needs a class verifylength to validate length) and so on....
try this
HTML
<form action="fake.php">Username*:
<input type="text" class="required verifylength" name="u" />
<br/>Email*:
<input type="text" class="required email" name="p" />
<br/>Street address:
<input type="text" class="numeric" name="s" />
<br/>Year of birth*:
<input type="text" class="required numeric" name="b" />
<br/>
<input type="submit" />
<br/>
</form>
JAVASCRIPT
document.forms[0].elements[0].focus();
document.forms[0].onsubmit = function () {
for (var i = 0; i < document.forms[0].elements.length; i++) {
var el = document.forms[0].elements[i];
if ((el.className.indexOf("required") != -1) && (el.value == "")) {
alert("missing required field");
el.focus();
el.style.backgroundColor = "yellow";
return false;
} else {
if (el.className.indexOf("verifylength") != -1) {
if (el.value.length < 5 || el.value.length > 10) {
alert("'" + el.value + "' must be 5-10 charater long");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
if (el.className.indexOf("email") != -1) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(el.value);
if (!emailTest) {
alert("email not valid");
el.focus();
el.style.backgroundColor = "yellow";
return false;
}
};
if ((el.className.indexOf("numeric") != -1) && (isNaN(el.value))) {
alert(el.value + " is not a number");
el.focus();
el.style.backgroundColor = "pink";
return false;
}
}
}
working fiddle
something alongs the lines of...
//username 5-10 chars
var uVal = document.getElementsByTagName("u").value;
if (uVal.length < 5 || uVal.length > 10) return false;
//email needs # and .
var eVal = document.getElementsByTagName("p").value;
if !(eVal.match('/.*#.*\./g')) return false;
//street starts w/ num
var sVal = document.getElementsByTagName("s").value;
if !(sVal.match('/^[0-9]/g')) return false;
i think the regex is off + untested :)
Here is your javascript validation object in work. Hope you can make some modification according to your need.
Style
<style>
.valid {border: #0C0 solid 1px;}
.invalid {border: #F00 solid 1px;}
</style>
HTML Form
<div>
<form id="ourForm">
<label>First Name</label><input type="text" name="firstname" id="firstname" class="" /><br />
<label>Last Name</label><input type="text" name="lastname" id="lastname" class="" /><br />
<label>Username</label><input type="text" name="username" id="username" class="" /><br />
<label>Email</label><input type="text" name="email" id="email" class="" /><br />
<input type="submit" value="submit" class="" />
</form>
</div>
Call script before closing tag
<script src="form_validation_object.js"></script>
form_validation_object.js
/*
to: dom object
type: type of event
fn: function to run when the event is called
*/
function addEvent(to, type, fn) {
if (document.addEventListener) { // FF/Chrome etc and Latest version of IE9+
to.addEventListener(type, fn, false);
} else if (document.attachEvent) { //Old versions of IE. The attachEvent method has been deprecated and samples have been removed.
to.attachEvent('on' + type, fn);
} else { // IE5
to['on' + type] = fn;
}
}
// Your window load event call
addEvent(window, 'load', function() {
/* form validation object */
var Form = {
validClass: 'valid',
inValidClass: 'invalid',
fname: {
minLength: 1,
maxLength: 8,
fieldName: 'First Name'
},
lname: {
minLength: 1,
maxLength: 12,
fieldName: 'Last Name'
},
username: {
minLength: 5,
maxLength: 10,
fieldName: 'Username'
},
validateLength: function(formElm, type) {
//console.log('string = ' + formElm.value);
//console.log('string length = ' + formElm.value.length);
//console.log('max length=' + type.maxLength);
//console.log(Form.validClass);
if (formElm.value.length > type.maxLength || formElm.value.length < type.minLength) {
//console.log('invalid');
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) == -1) {
if (formElm.className.indexOf(Form.validClass) != -1) {
formElm.className = formElm.className.replace(Form.validClass, Form.inValidClass);
} else {
formElm.className = Form.inValidClass;
}
}
//alert(formElm.className);
return false;
} else {
//console.log('valid');
//alert(formElm.className.indexOf(Form.validClass));
if (formElm.className.indexOf("\\b" + Form.validClass + "\\b") == -1) { // regex boundary to match whole word only http://www.regular-expressions.info/wordboundaries.html
//formElm.className += ' ' + Form.validClass;
//alert(formElm.className);
if (formElm.className.indexOf(Form.inValidClass) != -1)
formElm.className = formElm.className.replace(Form.inValidClass, Form.validClass);
else
formElm.className = Form.validClass;
}
return true;
}
},
validateEmail: function(formElm) {
var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
var emailTest = regEx.test(formElm.value);
if (emailTest) {
if (formElm.className.indexOf(Form.validClass) == -1) {
formElm.className = Form.validClass;
}
return true;
} else {
formElm.className = Form.inValidClass;
return false;
}
},
getSubmit: function(formID) {
var inputs = document.getElementById(formID).getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'submit') {
return inputs[i];
}
}
return false;
}
}
/* call validation object */
var ourForm = document.getElementById('ourForm');
var submit_button = Form.getSubmit('ourForm');
submit_button.disabled = 'disabled';
function checkForm() {
var inputs = ourForm.getElementsByTagName('input');
if (Form.validateLength(inputs[0], Form.fname)) {
if (Form.validateLength(inputs[1], Form.lname)) {
if (Form.validateLength(inputs[2], Form.username)) {
if (Form.validateEmail(inputs[3])) {
submit_button.disabled = false;
return true;
}
}
}
}
submit_button.disabled = 'disabled';
return false;
}
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
Working example at JSBin
http://jsbin.com/ezujog/1

Categories