I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.
Related
The phone number and the email must be valid.
This is a basic popup contact form without the phone number validation. I would like to validate the phone number. I heard about regex but i´m not sure how to implement in the code.
Since i don´t understand javascrip yet i hope you can help me.
<form action="#" method="post" id="form">
<h2>Contact Us</h2><hr/>
<input type="text" name="company" id="company" placeholder="Company"/>
<input type="text" name="name" id="name" placeholder="Name"/>
<input type="text" name="email" id="email" placeholder="Email"/>
<input type="text" name="phone" id="email" placeholder="Phone"/>
<a id="submit" href="javascript: check_empty()">Send</a>
</form>
function check_empty(){
if(document.getElementById('company').value == ""
|| document.getElementById('name').value == ""
||document.getElementById('email').value == ""
||document.getElementById('phone').value == "" ){
alert ("Please, fill the fields!");
}
else {
document.getElementById('form').submit();
}
}
//function to display Popup
function div_show(){
document.getElementById('abc').style.display = "block";
}
//function to check target element
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('abc');
var obj2 = document.getElementById('popup');
checkParent(target)?obj.style.display='none':null;
target==obj2?obj.style.display='block':null;
}
//function to check parent node and return result accordingly
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('abc'))
{
return false
}
else if(t==document.getElementById('close'))
{
return true
}
t=t.parentNode
}
return true
}
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>
please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>
I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.
I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}