Validating Input with Javascript - 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();">

Related

Basic Javascript onclick

here's my code, brand new to coding trying to get the box "points" to return the sum of pointSum if "Ben" is typed into the box "winner". Just trying to work on some basics with this project. Attempting to make a bracket of sorts
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
if (winnerOne = true){
pointSum+=firstRound
} else if (winnerTwo = true){
pointSum+=secondRound
} else if (winnerThree = true){
pointSum+=thirdRound
} else if (winnerFour = true){
pointSum+=fourthRound
} else if (winnerFive = true){
pointSum+=fifthRound
} else if (winnerSix = true){
pointSum+=finalRound
else
function tally() {if document.getElementById('winner') == "Ben" { winnerOne = true;
}
pointSum=document.getElementById("points").value;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
</body>
</html>
UPDATE***** new code, getting better, not returning console errors but still not getting anything in the "points" box upon clicking tally
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne == true;
}
pointSum = document.getElementById("points").value;
}
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<div class="updatePoints">
</div>
</body>
</html>
Your code has a few mistakes, lets change it a little bit!
First, you need to access 'value' atribbute of your winner element in your if statement, and surround all the statement in parenthesis
function tally() {
if (document.getElementById('winner').value == "Ben"){
winnerOne = true;
}
pointSum = document.getElementById("points").value;
}
Second, you use '==' to make comparison, you are using '=', it means that you are assign true to variables, and you're forgetting to put ';' at the end of lines! change this part:
if (winnerOne == true){
pointSum+=firstRound;
}
put all of your if/else like the example above!
Hint: when you are using if statement you can use like this:
if (winnerOne){ //you can omit == true, because if winnerOne is true, it will enter ind the if statement
//will enter here if winnerOne is true
}
if (!winnerOne){ //you can omit == false, because if winnerOne is not true, it will enter ind the if statement
//will enter here if winnerOne is false
}
You also have a left over else at the end of your if check which is invalid. You need to end the last else if statement with the };.
Are you trying to out put the text somewhere? I don't see any code that is handling this - you may want to add some HTML that will update like so:
<div class="updatePoints">
// leave empty
</div>
Then within your JavaScript you can always add some code to update the .updatePoints
var points = document.getElementByClass('updatePoints');
points.innerHTML = pointSum.value;
Have add some lines in your code and modify it with some comments. Can try at https://jsfiddle.net/8fhwg6ou/. Hope can help.
<HTLML>
<head>
<script>
var pointSum = 0;
var firstRound = 20;
var secondRound = 50;
var thirdRound = 100;
var fourthRound = 150;
var fifthRound = 250;
var finalRound = 300;
var winnerOne = false;
var winnerTwo = false;
var winnerThree = false;
var winnerFour = false;
var winnerFive = false;
var winnerSix = false;
function tally() {
var winner = document.getElementById("winner").value;
var firstWinner = "Ben";
if (winner == firstWinner){
winnerOne = true; // Use only one = symbol to assign value, not ==
pointSum = Number(document.getElementById("points").value); // moved from outside and convert to number
// This code will update point in Points box
document.getElementById("points").value = tally_pointsum(pointSum);
// The codes below will add the text in div, just remove the + sign if you don't like
document.getElementById("updatePoints").innerHTML += (tally_pointsum(pointSum) - pointSum) + " points added<br />";
}
}
// Wrap codes below become a function, lets call it tally_pointsum:
function tally_pointsum(pointSum) {
if (winnerOne == true){
pointSum+=firstRound;
} else if (winnerTwo){
pointSum+=secondRound;
} else if (winnerThree){
pointSum+=thirdRound;
} else if (winnerFour){
pointSum+=fourthRound;
} else if (winnerFive){
pointSum+=fifthRound;
} else if (winnerSix){
pointSum+=finalRound;
}
return pointSum; //return the sum to caller
}
</script>
</head>
<body>
<form>
Winner:
<input type="text" name="winner" id="winner" size="20">
Points:
<input type="text" name="points" id="points" size="20">
Submit
<button type= "button" onclick="tally()">Tally points</button>
</form>
<!-- change class="updatePoints" to id="updatePoints" for document.getElementById("updatePoints") -->
<div id="updatePoints">
</div>
Happy coding.

Javascript: submit button is not active when enter data to the form

I've picked up this code and it does not seem to work. The problem is the 'submit' button is not active when i try to click after i entered all the data to the form. Any help on where i am lacking? please
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="ourForm">
<label>First Name</label><input type="text" /><br />
<label>Last Name</label><input type="text" /><br />
<label>Email</label><input type="text" /><br />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
function addEvent(to, type, fn){
if(document.addEventListener){
to.addEventListener(type, fn, false);
} else if(document.attachEvent){
to.attachEvent('on'+type, fn);
} else {
to['on'+type] = fn;
}
};
var Form = {
validClass : 'valid',
fname : {
minLength : 1,
maxLength : 15,
fieldName : 'First Name'
},
lname : {
minLength : 1,
maxLength : 25,
fieldName : 'Last Name'
},
validateLength : function(formEl, type){
if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){
formEl.className = formEl.className.replace(' '+Form.validClass, '');
return false;
} else {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
}
},
validateEmail : function(formEl){
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(formEl.value);
if (emailTest) {
if(formEl.className.indexOf(' '+Form.validClass) == -1)
formEl.className += ' '+Form.validClass;
return true;
} else {
formEl.className = formEl.className.replace(' '+Form.validClass, '');
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;
}
};
addEvent(window, 'load', function(){
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.validateEmail(inputs[2])){
submit_button.disabled = false;
return true;
}
}
}
submit_button.disabled = 'disabled';
return false;
};
checkForm();
addEvent(ourForm, 'keyup', checkForm);
addEvent(ourForm, 'submit', checkForm);
});
</script>
</body>
</html>
I copied the code and tried the same code. It works. It might be that you filled all the three inputs but you did not put correct EMAIL that fulfills the EMAIL format(regex) in the code.
For example try to fill inputs with these three inputs someone, someone, someone#gmail.com; Submit is enabled

My form submits data even if it is invalid. But my validation works fine

My code follows:.
<!doctype html>
<html lang="en">
<head>
<title>Testing the textarea</title>
<style type="text/css"></style>
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
<div id="wrapper">
<span id="error_box" style="display:none;"></span>
<form name="storyTeller" method="get" action="#" onSubmit="return validateForm()">
<p class="title">
<label for="title">TITLE:</label>
<input type="text" id="title" name="title" required onBlur="validateTitle(title)"/>
</p>
<textarea name="entry" id="entry" rows="10" cols="45" onBlur="validateEntry(entry)">
</textarea>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Content of validation.js:
function validateTitle(title){/*validating the title*/
if (isNaN(document.getElementById('title').value)){
document.getElementById('title').style.background="#ccffcc";
document.getElementById('error_box').style.display="none";
return true;
}
else{
document.getElementById('error_box').innerHTML='Please enter a valid title';
document.getElementById('error_box').style.display="block";
document.getElementById('title').style.background="red";
return false;
}
}
function validateEntry(entry){/*validating the entry*/
var x=document.getElementById('entry').value;
x = x.trim();
if((x=="")||(x==null)){
document.getElementById('entry').style.background="red";
document.getElementById('error_box').innerHTML = 'Where is your story';
document.getElementById('error_box').style.display="block";
return false;
}
else{
document.getElementById('entry').style.background="#ccffcc";
document.getElementById('error_box').innerHTML='';
document.getELementById('error_box').style.display="none";
return true;
}
}
function validateForm(){/*validating the form*/
var error = 0;
if(!validateTitle('title')){
document.getElementById('error_box').style.display="block";
error++;
}
if(!validateEntry('entry')){
document.getElementById('error_box').style.display="block";
error++;
}
if(error > 0){
return false;
}
}
make the submit button as a normal button; and when it is clicked to call the final validation function, at the end of the function you must submit the form manually if everything is right
example :
<script>
function val(){
if(document.getElementById('tb').value != "")
document.getElementById('frm').submit();
else alert('fill the text field');
}
</script>
<form id="frm" action="#">
<input type="text" id="tb"/>
<input type="button" id="btn" value="submit" onclick="val()"/>
</form>
There is an error in your scrip in function validateEntry()
change line:
document.getELementById('error_box').style.display="none";
to line:
document.getElementById('error_box').style.display="none";
Modified your code so now it works better for both submit and blur events.
In your HTML source change both onblur attributes to onblur="validateEntry(this)" and then you can use this javascript:
function validateEntry(entry) { /*validating*/
var error_box = document.getElementById('error_box');
error_box.style.display = "none";
if (entry.name == "title") { // INPUT type="text"
if (!isNaN(entry.value)) {
error_box.innerHTML = 'Please enter a valid title';
error_box.style.display = "block";
entry.style.background = "#fee";
return false;
} else {
entry.style.background = "#ccffcc";
return true;
}
} else if (entry.name == "entry") { // TEXTAREA
var x = entry.value.trim();
if ((x == "") || (x == null)) {
error_box.innerHTML = 'Where is your story?';
error_box.style.display = "block";
entry.style.background = "#fee";
return false;
} else {
entry.style.background = "#ccffcc";
return true;
}
}
}
function validateForm() { /*validating the form*/
var form = document.forms['storyTeller'];
var error_box = document.getElementById('error_box');
var error = 0;
var error_msg = '';
if (!validateEntry(form['title'])) {
error++;
error_msg += error_box.innerHTML + '<br/>';
}
if (!validateEntry(form['entry'])) {
error++;
error_msg += error_box.innerHTML;
}
if (error > 0) {
error_box.innerHTML = error_msg;
error_box.style.display = "block";
return false;
} else {
error_box.style.display = "none";
return true;
}
}
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

Disable/Enable Submit Button until all forms have been filled

I want my form submit button to be disabled/enabled depending on if the form is completely filled.
When the inputs are filled, the disabled button changes to enabled. That works great.
But I would like it to disable the button when an input gets emtied.
This is my script:
<script type="text/javascript" language="javascript">
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
}
</script>
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.
Just add an else then:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
Put it inside a table and then do on her:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";
function checkForm() {
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>JavaScript</title>
</head>
<body>
<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>
<form onkeyup="checkForm()" autocomplete="off" novalidate>
<input type="text" name="fname" placeholder="First Name" required><br><br>
<input type="text" name="lname" placeholder="Last Name" required><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</body>
</html>
Example explained:
We create a variable to store all the input elements.
var inp = document.getElementsByTagName("input");
We create another variable to store the button element
var btn = document.getElementById("btn");
We loop over the collection of input elements
for (var i = 0; i < inp.length; i++) {
// Code
}
Finally, We use the checkValidity() method to check if the input elements
(with a required attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
You can enable and disable the submit button based on the javascript validation below is the validation code.
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>

Categories