onsubmit attribute not work - javascript

Hello I trying to validate my form using onsubmit attribute. But it does not work. And the funniest thing in this story - this works properly only 2 days ago.
Form tag :
<form action="../actionHandlers/registrationHandler.php" onsubmit="return validateRegistrationForm()" method="post" name="reg_form" enctype="multipart/form-data" id="reg_form">
Validate function:
function validateRegistrationForm() {
var errors = [];
if (document.forms['reg_form']['username'].value.length == 0) {
var usernameErrorMessage = localStorage.getItem('emptyLoginError');
errors.push(usernameErrorMessage);
}
if (document.forms['reg_form']['password'].value.length == 0) {
var passwordErrorMessage = localStorage.getItem('emptyPasswordError');
errors.push(passwordErrorMessage);
}
if (!validateEmail(document.forms['reg_form']['email'].value)) {
var emailErrorMessage = localStorage.getItem('emailInvalidError');
errors.push(emailErrorMessage);
}
if (errors.length > 0) {
var htmlErrors = '';
for (var i = 0; i < errors.length; i++) {
htmlErrors += errors[i] + "<br />";
}
document.getElementById("error_message").innerHTML = htmlErrors;
return false;
} else {
return true;
}
}
Where is my mistake? Please help)
Validate email:
function validateEmail(email) {
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(email);
}
Inputs:
<div>
<label for="username" id="username_label"><?php echo $languageArray['USERNAME'] ?></label><span id="required_mark">*</span><br/>
<input type="text" name="username" id="username_field" class="input_form_fields">
</div>
<div>
<label for="password"><?php echo $languageArray['PASSWORD'] ?></label><span id="required_mark">*</span><br/>
<input type="password" name="password" id="password_field" class="input_form_fields">
</div>
<div>
<label for="email"><?php echo $languageArray['EMAIL'] ?></label><span id="required_mark">*</span><br/>
<input type="text" name="email" id="email_field" class="input_form_fields">
</div>

Try this code, I have tested it and its working:
<form action="../actionHandlers/registrationHandler.php" onsubmit="return validateRegistrationForm()" method="post" name="reg_form" enctype="multipart/form-data" id="reg_form">
<div>
<label for="username" id="username_label"><?php echo (isset($languageArray['USERNAME']) ? $languageArray['USERNAME'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="text" name="username" id="username_field" class="input_form_fields">
</div>
<div>
<label for="password"><?php echo (isset($languageArray['PASSWORD']) ? $languageArray['PASSWORD'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="password" name="password" id="password_field" class="input_form_fields">
</div>
<div>
<label for="email"><?php echo (isset($languageArray['EMAIL']) ? $languageArray['EMAIL'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="text" name="email" id="email_field" class="input_form_fields">
</div>
<input type="submit">
</form>
And the JS:
function validateEmail(email) {
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(email);
}
function validateRegistrationForm(e) {
var errors = [];
if (document.forms['reg_form']['username'].value.length == 0) {
var usernameErrorMessage = localStorage.getItem('emptyLoginError') ? localStorage.getItem('emptyLoginError') : "username error";
errors.push(usernameErrorMessage);
}
if (document.forms['reg_form']['password'].value.length == 0) {
var passwordErrorMessage = localStorage.getItem('emptyPasswordError') ? localStorage.getItem('emptyPasswordError') : "password error";
errors.push(passwordErrorMessage);
}
if (!validateEmail(document.forms['reg_form']['email'].value)) {
var emailErrorMessage = localStorage.getItem('emailInvalidError') ? localStorage.getItem('emailInvalidError') : "email error";
errors.push(emailErrorMessage);
}
if (errors.length > 0) {
var htmlErrors = '';
for (var i = 0; i < errors.length; i++) {
htmlErrors += errors[i] + "<br />";
}
if(document.getElementById("error_message")){
document.getElementById("error_message").innerHTML = htmlErrors;
}
return false;
} else {
return true;
}
}
The way I see it the problem were caused by any of the following:
localStorage.getItem notice that you don't even check to see if the key exists.
echo $languageArray['PASSWORD'] again there is no check at all, although I'm sure its not php error but its good to check before you echo.
document.getElementById("error_message"), well you use the innerHTML but the document.getElementById my return undefined.
Conclusion:
The code should work.
But:
You say it worked before, I'm thinking you have touched the html in one way or another, if its not the html check the localStorage keys.

Related

How can i make innerHtml writes error only once?

I have a problem, I made a form validation in javascript and after all validation checks I put innerHtml += "actually error message" and the problem is how many times I click the submit button it writes out the message. Someone can help me to solve this? Or make this more elegant or better logic. I'm a beginner.
function regvalidate() {
var errortable = document.getElementById('log');
var x = document.forms["regform"]["username"].value;
var y = document.forms["regform"]["email"].value;
var z = document.forms["regform"]["pass1"].value;
var b = document.forms["regform"]["pass2"].value;
if (x == "" || y == "" || z == "" || b == "") {
errortable.innerHTML = 'Cant be empty field';
return false;
}
var regexEmail = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("email");
if (regexEmail.test(email.value)) {} else {
errortable.innerHTML += 'Invaild email address';
return false;
}
password1 = regform.pass1.value;
password2 = regform.pass2.value;
if (password1 != password2) {
errortable.innerHTML += 'Two pass dosent match';
return false;
}
}
<div id="log"></div>
<form id="regform" class="form-signin" action="#" method="post">
<input type="text" id="username" class="form-control" placeholder="username" name="username">
<input type="email" id="email" class="form-control" placeholder="email" name="email">
<input type="password" id="pass1" class="form-control" placeholder="password" name="password_1">
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2">
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" onClick="return regvalidate()" name="register_btn">Register</button>
</form>
just remove the + before =like the following
errortable.innerHTML += 'Two pass dosent match';
or do it like
errortable.innerHTML = '';
errortable.innerHTML += 'Two pass dosent match';

i have a error while validating my html form with javascript

This is my javascript function.
function shortCutValidation() {
//var txtObjList = document.getElementsByTagName("input");
//for (var i = 0; i < txtObjList.length; i++) {
// if (txtObjList[i].getAttribute("type") == "text" && this.value != "") {
// // success for i+1 textbox
// }
// else {
// $(txtObjList).closest(".errortext").css("display", "block");
// }
//}
var data = document.getElementsByClassName("w-input");
if (data.length > 0) {
console.log("yes you are in");
for (var i = 0; i < data.length; i++) {
var myvalue = document.getElementsByClassName("w-input");
if (myvalue[i].value == '') {
console.log("yes value is empty"+myvalue[i].value);
$(myvalue[i]).next(".errortext").css("display", "block");
}
else {
console.log("thats ok");
$(data[i]).next(".errortext").css("display", "none");
}
console.log(i);
}
}
}
This is my html code.
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">First Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="hidden" id="id" name="id" value="" />
<input type="text" class="w-input" name="fname" id="fname" />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
<div class="myformgrp w-clearfix w-col">
<div class="w-col w-col-2 w-col-medium-3 w-col-small-12">
<label for="firstname" class="verticle-centerinline">Last Name </label>
</div>
<div class="w-col w-col-10 w-col-medium-9 w-col-small-12">
<input type="text" class="w-input" name="lname" id="lname" /><br />
<div class="errortext" style="display:none">required field</div>
</div>
</div>
The problem is that I can't validate all the text box at once
but my for loop is working as expected.
I use jQuery to call the shortCutValidation function.
All I want is when my blur event is called to validate all the text box at once and the error massage should be displayed.
Try This
function validateFormOnSubmit(contact) {
reason = "";
reason += validateName(contact.name);
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validatePet(contact.pet);
reason += validateNumber(contact.number);
reason += validateDisclaimer(contact.disclaimer);
if (reason.length > 0) {
return false;
} else {
return false;
}
}
// validate required fields
function validateName(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Red';
document.getElementById('name-error').innerHTML = "The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML = '';
}
return error;
}
// validate email as required field and format
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error = "";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (email.value == "") {
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter an email address.";
var error = "2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Red';
document.getElementById('email-error').innerHTML = "Please enter a valid email address.";
var error = "3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Red';
var error = "4";
document.getElementById('email-error').innerHTML = "Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML = '';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Red';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Red';
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Red';
} else {
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
}
return error;
}
function validatePet(pet) {
if ((contact.pet[0].checked == false) && (contact.pet[1].checked == false) && (contact.pet[2].checked == false)) {
document.getElementById('pet-error').innerHTML = "Pet required";
var error = "2";
} else {
document.getElementById('pet-error').innerHTML = '';
}
return error;
}
function validateNumber(number) {
var num = document.forms["contact"]["number"];
var y = num.value;
if (!isNaN(y)) {
//alert('va');
if (y < 0 || y > 50) {
//Wrong
number.style.background = 'Red';
document.getElementById("number-error").innerHTML = "Must be between 0 and 50.";
var error = "10";
} else {
//Correct
number.style.background = 'White';
document.getElementById("number-error").innerHTML = "";
}
return error;
} else {
document.getElementById("number-error").innerHTML = "Must be a number.";
var error = "3";
}
return error;
}
function validateDisclaimer(disclaimer) {
var error = "";
if (document.getElementById("disclaimer").checked === false) {
document.getElementById('disclaimer-error').innerHTML = "Required";
var error = "4";
} else {
document.getElementById('disclaimer-error').innerHTML = '';
}
return error;
}
.error {
color: #990000;
}
input::-webkit-input-placeholder {
color: white !important;
}
input:-moz-placeholder { /* Firefox 18- */
color: white !important;
}
input::-moz-placeholder { /* Firefox 19+ */
color: white !important;
}
input:-ms-input-placeholder {
color: white !important;
}
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<div>
<label>First Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error" class="error"></div>
</div>
<div>
<label>Nickname</label>
<input placeholder="Nickname" type="text" name="nickname" id="nickname" tabindex="2" autofocus />
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error" class="error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="tel" name="phone" id="phone" tabindex="4" autofocus />
<div id="phone-error" class="error"></div>
</div>
<div>
<label>I prefer</label>
<input type="radio" name="pet" id="Dogs" tabindex="5" autofocus />Dogs
<input type="radio" name="pet" id="Cats" tabindex="6" autofocus />Cats
<input type="radio" name="pet" id="Neither" tabindex="7" autofocus />Neither
<div id="pet-error" class="error"></div>
</div>
<div>
<label>My favorite number between 1 and 50</label>
<input placeholder="Favorite number between 1 and 50" type="text" name="number" id="number" tabindex="8" autofocus />
<div id="number-error" class="error"></div>
</div>
<div>
<label>Disclaimer</label>
<input type="checkbox" name="disclaimer" id="disclaimer" tabindex="9" autofocus />I confirm that all the above information is true.
<div id="disclaimer-error" class="error"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="10">Send</button>
</div>
</form>
Happy Coding

How to print error message under respective input field using javascript validation in php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>

Form sent but validation has error

My form is not working well. Although there's error, it's still able to go through. Errflag is 1 but it goes to the '0'. Appreciate if someone can shed some light.
JSFiddle: https://jsfiddle.net/rezasan/xxqtuc7d/
HTML
<form id="contact_form">
<div class="medium-6 columns">
<input type="hidden" name="sourcepage" value="Index Page">
<input type="text" placeholder="NAME" name="name" id="name" required />
<input type="email" placeholder="EMAIL" name="email" id="email" required/>
<input type="text" placeholder="TEL" name="phone" id="phone" required/>
<select name="services" id="serviceslist">
<option value="services" selected>SERVICES</option>
<option value="botox">Botox</option>
<option value="filler">Filler</option>
<option value="Ultherapy">Ultherapy</option>
<option value="coolsculpting">CoolSculpting</option>
<option value="threadlift">Thread Lift</option>
<option value="others">Others</option>
</select>
<div class="errtext"></div>
</div>
<div class="medium-6 columns">
<textarea rows="6" cols="55" name="message" id="message" placeholder="Please enter your enquiries"></textarea>
<input type="submit" style="float:right;" id="submit" name="submit" class="formelement-submit">
</div>
</form>
JAVASCRIPT
function trimStr (str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function checkTFieldValue(target,value,errorclass) {
if(trimStr($(target).val()) == value) {
$(target).addClass(errorclass);
return 1;
} else{
return 0;
}
}
function checkSFieldValue(target,value,errorclass) {
if(value == "SERVICES") {
$(target).addClass(errorclass);
return 1;
} else{
return 0;
}
}
function checkEmailValue(target,value,errorclass) {
var err = 0;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(trimStr($(target).val()) == value) {
$(target).addClass(errorclass);
err = 1;
} else if(!emailReg.test($(target).val())) {
$(target).addClass(errorclass);
err = 1;
}
return err;
}
$('#contact_form').append('<input type="hidden" name="jsauth" value="dryga-f"/>');
$('.formelement-submit').click(function(e){
e.preventDefault();
e.stopPropagation();
var errflag = 0;
var counter = 0;
$('.formerror').removeClass('formerror');
$('.errtext').empty();
var e = document.getElementById("serviceslist");
var strUser = e.options[e.selectedIndex].text;
errflag = checkTFieldValue('#name','','formerror');
errflag = checkEmailValue('#email','','formerror');
errflag = checkTFieldValue('#phone','','formerror');
errflag = checkSFieldValue('#serviceslist',strUser,'formerror');
errflag = checkTFieldValue('#message','','formerror');
if(errflag == 1){
$('.errtext').html('<p>*Please fill in all the required fields</p>');
}
if(errflag == 0){
$('.errtext').html('No error');
}
});
if #message is valid then it overwrites all others with 0.
you need to += the errflag and check for >:-
errflag += checkTFieldValue('#name','','formerror');
errflag += checkEmailValue('#email','','formerror');
errflag += checkTFieldValue('#phone','','formerror');
errflag += checkSFieldValue('#serviceslist',strUser,'formerror');
errflag += checkTFieldValue('#message','','formerror');
if(errflag > 0){
$('.errtext').html('<p>*Please fill in all the required fields</p>');
}
else {
$('.errtext').html('No error');
}
also, as #MarcoScabbiolo suggests, use submit instead of click.
When using forms, it's better to attach your validation handler into the form's submit event, not on the click of the submit button. Because there are other ways the form could submit, like pressing enter on an input.
Change
$('.formelement-submit').click(
To
$('#contact_form').on('submit',
It's working in this fiddler

Simple JavaScript validation not working?

Not sure why this isn't working.
<!DOCTYPE html>
<html>
<head>
<title>Player 1</title>
<link rel="stylesheet" type="text/css" href="playerOne.css">
</head>
<body>
<div id="heading">
<h>Player 1</h>
</div>
<form name="playerInfo" onsubmit="return validate()" method="post">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label id="inPID">Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus >
<br>
<br>
<label id="inFN">First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name" >
<br>
<br>
<label id="inLN">Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name" >
<br>
<br>
<label id="inEA">Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label id="inPW">Password:</label>
<br>
<input type="password" name="password" class="input" id="pass" >
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate" >
</fieldset>
<hr>
</form>
<div id="error"></div>
<script>
function testVal(){
return false;
}
function validate() {
var message;
var test = true;
message = document.getElementById("error");
message.innerHTML += "";
var x = document.getElementById("id");
if(x.value == ""|| x.value == null||x.value== "Player ID") {
x.style.backgroundColor = "#FF0000";
message.innerHTML += "Player ID is missing\n";
test = false;
}else{
}
var x = document.getElementById("fname");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "First name is missing\n";
test = false;
}else{
}
var x = document.getElementById("sname");
if(x.value == "") {
x.style.borderColor ="#FF0000";
message.innerHTML += "Surname is missing\n";
test = false;
}else{
}
var x = document.getElementById("email");
if(x.value == "") {
x.style.borderColor = "#FF0000";
message.innerHTML += "Email is missing\n";
test = false;
}else{
}
var x = document.getElementById("pass");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "Password is missing\n";
test = false;
}else{
}
return test;
}
</script>
</body>
So it should change the color of the borders to red if the input is incorrect( or empty), and inform the user in a div. For some reason, the code is always submitting without recognizing the errors. Also I'm a beginner at JavaScript (and html) so if anyone has any input on improving this code it would be appreciated.
EDIT: Apologies. I uploaded the wrong version of the code the testval function was only there to check if the onsubmit was working correctly, and the validate function is now called onsubmit, which is where/when it should be but is not working.
EDIT 2: Thank you for your help on the format and correct tag use. I have edited it as to your recommendations, however the actual validating (function) is still not working, despite the inclusion of quotation marks.
references:
http://www.w3schools.com/js/js_validation.asp
http://www.tutorialspoint.com/javascript/javascript_form_validations.htm
Look at your console errors.
First is a typo in testVal - "retrun" instead of "return".
Next up, strings need to be quoted so x.style.borderColor = #FF0000; needs to be x.style.borderColor = "#FF0000";
Beyond that, you don't actually seem to be calling validate() in the code provided. Also, look into using the placeholder attribute for input elements, or - possibly more appropriate - the label element, rather than your approach of putting the label inside the value of each input.
You gave the same name x for JavaScript variables. I also fixed your form a little.
Some suggestions:
The \n in a.innerHTML += "Some string\n" doesn't work. Use "<br />" instead
Different names for different variables please
Use the placeholder attribute instead of value to suggest the user
Use the message variable to hold the error message instead of setting the innerHtml directly because Javascript uses Pass By Value (see reference)
When you get more acquainted with Javascript, you would want to learn jQuery. It provides a great API for easier time coding as well as make Html traversal, event handling and Ajax much simpler. http://www.w3schools.com/jquery/default.asp is a great place to learn jQuery.
Fixed Javascript and Html:
function validate() {
var message = "";
var test = true;
var id = document.getElementById("id");
if (id.value == "" || id.value == null) {
id.style.backgroundColor = "#FF0000";
message += "Player ID is missing<br />";
test = false;
} else {
}
var fname = document.getElementById("fname");
if (fname.value == "" || fname.value == null) {
fname.style.borderColor = "#FF0000";
message += "First name is missing<br />";
test = false;
} else {
}
var sname = document.getElementById("sname");
if (sname.value == "" || sname.value == null) {
sname.style.borderColor = "#FF0000";
message += "Surname is missing<br />";
test = false;
} else {
}
var email = document.getElementById("email");
if (email.value == "" || email.value == null) {
email.style.borderColor = "#FF0000";
message += "Email is missing<br />";
test = false;
} else {
}
var x = document.getElementById("pass");
if (x.value == "" || x.value == null) {
x.style.borderColor = "#FF0000";
message += "Password is missing<br />";
test = false;
} else {
}
if (test == true) {
document.alert("OK");
// document.getElementById("frmPlay").submit();
} else {
document.getElementById("error").innerHtml = message;
}
}
<form name="playerInfo" onsubmit="validate()" method="post" id="frmPlay">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label>Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus>
<br>
<br>
<label>First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name">
<br>
<br>
<label>Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label>Password:</label>
<br>
<input type="password" name="password" class="input" id="pass">
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate">
</fieldset>
<hr>
</form>
<div id="error"></div>

Categories

Resources