Form validation: remove error after onkeydown in input - javascript

I am working on my first for validation, really basic.
If you leave the 'username' input blank it will turn the username input border red and also place an alert icon in the input.
I am trying to 'remove' what was added when the validation failed as soon as the user starts typing in the input that caused the error.
So the scenario is: The user leaves Username blank, clicks Submit and then the border of the Username input goes red and an error icon appears. They then go back and they add their username into the Username input after the first character they type into the Username box I want the red border and error icon to disappear.
However my attempts have failed
My Fiddle
JS
function contactForm() {
var theForm = document.forms.contact;
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
theForm.onsubmit = function() {
if (theForm.username.value === '') {
errorUsername.style.display = 'block';
usernameInput.className = 'form__input form__input--red rounded-4';
return false;
} else {
theForm.username.onkeydown = function() {
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
};
return true;
};
};
};
contactForm();
HTML
<form name="contact" action="#" novalidate>
<div class="input__holder">
<input id="username" name="username" type="text" class="form__input rounded-4" placeholder="Username">
<div id="username-error" class="input__error">!</div>
</div>
<div class="input__holder">
<input name="password" type="password" class="form__input rounded-4" placeholder="Password">
</div>
<div class="input__holder">
<input name="email" type="text" class="form__input rounded-4" placeholder="E-mail">
</div>
<button type="submit" id="" class="submit-button rounded-4">Submit</button>
</form>
CSS
Too long, in Fiddle :)

You can add something like this on javascript
document.onkeyup = function() {
var errorUsername = document.getElementById('username-error');
var usernameInput = document.getElementById('username');
if (usernameInput.value.length === 0) return;
errorUsername.style.display = 'none';
usernameInput.className = 'form__input rounded-4';
}
Here the fiddle:
https://jsfiddle.net/12apmo5j/12/
I think this solves your problem :)

Related

return true from javascript then form continue to submit

i have php page and javascript, the page is contact us form and before submit button there is captcha when form submit it checks captcha if it validate return true else alert and create again captcha but it doesn't work when it return true after that nothing happen
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" id="demo-form" onsubmit="validateCaptcha()" method="POST" enctype="multipart/form-data" >
<h3>Quick Contact</h3>
<h4>Contact us today, and get reply with in 24 hours!</h4>
<input type="hidden" name="action" value="submit">
<input placeholder="Your name" name="name" id="name" type="text" tabindex="1" required autofocus><br>
<input placeholder="Your Email Address" name="email" id="mail" type="email" tabindex="2" required><br>
<input placeholder="Subject" id="sub" name="subject" type="text" tabindex="3" required><br>
<input placeholder="Mobile Number" name="number" pattern="^((\+92)|(0092)|(0))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$" id="contactInformation" type="tel" tabindex="4" oninvalid="this.setCustomValidity('Enter mobile number like: 03001234567')"
oninput="this.setCustomValidity('')" > <br>
<textarea placeholder="Type your Message Here...." tabindex="6" name="message" id="msg" tabindex="5" required></textarea><br>
<div id="captcha">
</div><input type="text" placeholder="Enter Captcha Code Here" id="cpatchaTextBox"/><br>
<input name="submit" type="submit" value="Submit" tabindex="7" id="contact-submit" data-submit="...Sending" /><br>
<button type="reset" name="reset" tabindex="8" id="contact-reset">Clear Form</button>
</form>
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$subject=$_REQUEST['subject'];
$number=$_REQUEST['number'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($subject=="")||($number=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$msg= "Name: ".$name."\nContact Number: ".$number."\n".$message ;
mail("xyz#gmail.com", $subject, $msg , $from);
echo '<script type="text/javascript">',
'alert("EMAIL SENT..!");',
'setTimeout(function(){',
' window.location.href = "thanks.php";',
' }, 50);',
'</script>'
;
}
}
?>
</div>
</section>
</div>
<br/>
</div>
</div>
</div>
// JavaScript Document
var code;
function createCaptcha() {
//clear the contents of captcha div first
document.getElementById('captcha').innerHTML = "";
var charsArray =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#!#$%^&*";
var lengthOtp = 6;
var captcha = [];
for (var i = 0; i < lengthOtp; i++) {
//below code will not allow Repetition of Characters
var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
if (captcha.indexOf(charsArray[index]) == -1)
captcha.push(charsArray[index]);
else i--;
}
var canv = document.createElement("canvas");
canv.id = "captcha";
canv.width = 100;
canv.height = 50;
var ctx = canv.getContext("2d");
ctx.font = "25px Georgia";
ctx.strokeText(captcha.join(""), 0, 30);
//storing captcha so that can validate you can save it somewhere else according to your specific requirements
code = captcha.join("");
document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
event.preventDefault();
if (document.getElementById("cpatchaTextBox").value == code) {
return true;
}else{
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
kindly if anyone can do that for me i just want, when captcha validate the form submit and email sent to the person.
There are multiple ways to handle this, one of the simpler solution is to cast event.preventDefault() only when needed.
No need to return anything.
function validateCaptcha() {
if (document.getElementById("cpatchaTextBox").value != code) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
WORKING DEMO CAPTCHA OK
function validateCaptcha() {
const captchaMock = false; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
WORKING DEMO CAPTCHA NOT OK
function validateCaptcha() {
const captchaMock = true; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
onsubmit="validateCaptcha()"
should be
onsubmit="return validateCaptcha()"
to prevent the return value of validateCaptcha being thrown away. In addition, validateCaptcha needs to return boolean false to prevent form submission - returning some other falsey value such as undefined doesn't work.
You can also pass the event object to the validation routine using
onsubmit="return validateCaptcha( event)"
which allows cancelling the event in the validation routine using event methods called on the event argument.
However, adding event handlers in HTML is error-prone, and adding submit event handlers to the form in JavaScript using
formObject.addEventListener("submit", submitHandler, true);
may be preferable - the submit handler gets called with event as its argument.

Form Validation not responding correctly

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.

Make form validation via custom attributes

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>

Using JavaScript to validate form both onblur and when pressing submit

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.

Validating form after error has been shown

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;
}

Categories

Resources