Javascript Form Validation Event - javascript

)
I am trying to validate a form using Javascript, i would like the span to update when the string length is a certain amount of characters
<form id="contact">
<input id="name" name="name" type="text" class="feedback-input" placeholder="Name"/> <span id="spanName"> </span>
<input name="email" type="text" class="feedback-input" placeholder="Email" />
<textarea name="text" class="feedback-input" placeholder="Message..."></textarea>
<input type="submit" value="SUBMIT"/>
</form>
window.onload = function () {
var name = document.getElementById("name");
var nameVal = name.value;
var spanName = document.getElementById("spanName");
spanName.innerHTML = "✗";
name.addEventListener('keydown', function () {
validate();
});
function validate() {
console.log(name);
console.log(nameVal);
if (nameVal.length > 0) {
spanName.innerHTML = "✔";
} else if (nameVal.length > 8) {
spanName.innerHTML = "name is to long";
} else {
spanName.innerHTML = "yolo";
}
console.log(nameVal);
}
}

Variable scope is important.
Inside window.onload you declare three variables … and only use name once, to assign a value to onkeyup.
Inside validate you use name, which is a global variable already provided by the browser (it is not the variable you declared that is local to the other function). This is a string, so its length never changes.
// Create an IIFE to create a new (non-global) scope for all your variables.
(function() {
// Declare your variables at a level all the functions can reach them
var spanName, name;
// Get the DOM elements when the load event fires
function getDomElements() {
name = document.getElementById("contact").elements.name;
spanName = document.getElementById("spanName");
name.addEventListener("keyup", validate);
}
window.addEventListener("load", getDomElements);
// Define your validation function
// Check the VALUE of the form control, not the form control itself
function validate() {
// Make sure you exclude values you want a later condition to match
if (name.value.length > 0 & name.value.length <= 8) {
spanName.innerHTML = "✔";
} else if (name.value.length > 8) {
spanName.innerHTML = "name is to long";
} else {
spanName.innerHTML = "yolo";
}
}
})();
<form id="contact">
<input id="name" name="name" type="text" class="feedback-input" placeholder="Name" /> <span id="spanName"> </span>
<input name="email" type="text" class="feedback-input" placeholder="Email" />
<textarea name="text" class="feedback-input" placeholder="Message..."></textarea>
<input type="submit" value="SUBMIT" />
</form>

Sorry, this is an answer:
var contact, spanName;
window.onload = function () {
spanName = document.getElementById("spanName");
contact = document.getElementById("name");
contact.onkeyup = validate;
}
function validate() {
var name = contact.value;
var length = name.length;
if (length > 0 && length <=8) {
spanName.innerHTML = "✔";
} else if (length > 8) {
spanName.innerHTML = "name is to long";
} else {
spanName.innerHTML = "yolo";
}
}
Does it work to you?

Related

How do I remove "undefined" when auto-filling a form?

function validate() {
var errMsg = "";
var result = true;
var fname = document.getElementById("fname").value;
if (!fname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your first name correctly.\n";
result = false;
}
if (errMsg) {
alert(errMsg);
}
if (result) {
function storeBooking(
fname
) {
sessionStorage.fname = fname;
}
function getBooking() {
if (sessionStorage.fname != undefined) {
document.getElementById("confirm_fname").textContent = sessionStorage.fname;
}
}
function prefillcard()
{
document.getElementById("fname").value = sessionStorage.fname;
}
window.addEventListener("DOMContentLoaded", prefillcard);
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
<form action="apply.html" method="post" id="regform">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.." required="required" maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<input type="submit" value="Apply">
</form>
I've set up some code to auto-fill a form if the user had already filled the form in the same browser session and then revisited the form. The only problem is that there is a placeholder, which you need to delete before putting in an input, is there and I don't know how to get rid of it. "Undefined" comes up when you fill the form in the first time. How do I get rid of this?
Note: no jQuery or inline JavaScript.
To store values in session use
window.sessionStorage.setItem("Name", Value));
and to retrieve value from session use
window.sessionStorage.getItem("Name");
Sample code below
function prefillcard() {
if (window.sessionStorage.getItem("fname")) {
var fnm = window.sessionStorage.getItem("fname");
document.getElementById("fname").value = fnm;
}
}
and to set Session value use
var fnm = document.getElementById("fname").value;
window.sessionStorage.setItem("fname", fnm));

How can I verify form passwords match using JavaScript?

I have a basic html form with password and verify password fields. I want to only allow users to continue if passwords match. If passwords do not match, I want there to be a notification to the user.
I think that what I currently have is close, but the JS still doesn't appear to do anything.
HTML
<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password"/><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword"/><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
JS
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
There are some issues that can come from putting the javascript call in the HTML.
In your case, the function was probably defined after the HTML, so the element didn't have access to it.
You can use this instead:
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username" /><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password" /><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword" /><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
Here is an example. I created a passwordGroup constructor to centralize the information. This way it's easier to write tests also.
var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');
// PasswordGroup constructor
var PasswordGroup = function () {
this.password = '';
this.passwordConfirmation = '';
};
// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
this.password = data.password;
this.passwordConfirmation = data.passwordConfirmation;
};
// method to check the password's equality
PasswordGroup.prototype.match = function() {
return !!(this.password
&& this.passwordConfirmation
&& this.password === this.passwordConfirmation);
};
/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
if(passwordGroup.match()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', 'disabled');
}
}
// passwordGroup instance
var passwordGroup = new PasswordGroup();
// objecto to store the current values
var passwordsValues = {
password: '',
passwordConfirmation: '',
};
// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
var target = e.target;
var targetValue = target.value;
if(target.dataset.hasOwnProperty('password')) {
passwordsValues.password = targetValue;
} else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
passwordsValues.passwordConfirmation = targetValue;
}
passwordGroup.setValues(passwordsValues);
validateSubmit();
};
// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
display: block;
}
<form action="" name='account'>
<input type="text" placeholder="name" />
<input type="password" data-password placeholder="password"/>
<input type="password" data-password-confirmation placeholder="repeat password"/>
<button type="submit" disabled="disabled">Enviar</button>
</form>
<p data-message></p>

Make Javascript write on page after submit button pressed

Here is a bit of code I have sourced from w3schools which shows that whenever a name is over 10 characters, the page should add a bit of text, in this case, it should add on "hi", but instead, it removes everything from the page and goes onto a new page and only displays "hi". How can I resolve this?
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.write("hi");
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
</body>
</html>
Simply put, don't use document.write(). If you read the nice orange text at the top of the documentation, you'll see why:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
document.write() should only be used while a page is loading, to ouput while it's creating the webpage, and should not be used afterwards. Consider creating a div, and writing to there instead:
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.getElementById('result').innerHTML = 'Fname is > 10!';
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
} else {
alert('Submitted Successfully!');
return false; // Returning false here just for SO Code Snippet
}
}
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
<div id="result"></div>
</form>
Additionally, I notice you're setting submitOK = "true". Javascript does have booleans (See this also). Why not use that instead?
submitOK = true;
if (fname.length < 10) {
alert('Your name should be more than 10 characters');
submitOK = false;
}
if (submitOK) { // Same as "if (submitOK == true)"
//Good to go
}

what is the correct way to validate form with javascript

should i put "submit" instead "form_name" in the last block of code? what is the correct way?
thanks!
function check() {
var title = document.getElementById("title");
var content = document.getElementById("content");
if (title == "") {
alert("title is required");
return false;
}
if (content == "") {
alert("content is required");
return false;
}
var submit = document.getElementById("form_name");
submit.submit();
}
this is my form
<form action="#" method="post" id="form_name" name="form_name">
<input type="text" name="title" id="title" />
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<input type="submit" value="Submit" id="submit" name="submit" onclick="return check();"/>
</form>
First you are selecting an element and acting like it is the value
var title = document.getElementById("title"); <-- DOM element
if (title == "") { <-- checking the DOM against a string.
You should be using .value to get what was entered.
Next you are submitting the form.... but you clicked on a submit button inside of the form so that will submit the form. So that is not needed.
function check() {
var title = document.getElementById("title").value;
var content = document.getElementById("content").value;
if (!title.trim().length) {
alert("title is required");
return false;
else if (!content.trim().length) {
alert("content is required");
return false;
}
return true
}
And never name anything submit, it just leads to problems.
In most recent browsers you have more power to use
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}else{
document.getElementById("demo").innerHTML = "";
}
}
<input id="id1" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
Reference:
https://www.w3schools.com/js/js_validation_api.asp

Individual error messages for empty form fields using JavaScript

I need to validate my form using JavaScript because iPhone / Safari do not recognize the required attribute. I want individual error messages to appear below each empty input field.
My code works, but the individual error message does not disappear when the field is filled in. Also, I would like all messages to appear initially, for all empty fields (not one by one). I am very very new to JavaScript, sorry.
My HTML:
<form onsubmit="return validateForm()" method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
And my JavaScript:
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else {return true;}
}
</script>
Thanks for your help.
Here is a solution that displays all relevant errors when the form is first submitted, and removes an error when the user modifies text in the relevant input element.
To get it to display all of the errors on first run, I used if statements instead of if else, and used a flag to determine whether the form should be submitted. To remove the warnings when the input is modified, I bound the onkeyup events of the inputs.
I ended up removing the required attributes on the inputs so that the demonstration will work in a modern browser that supports them.
Live Demo:
document.getElementById("english_registration_form").onsubmit = function () {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
var submit = true;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
submit = false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
submit = false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
submit = false;
}
return submit;
}
function removeWarning() {
document.getElementById(this.id + "_error").innerHTML = "";
}
document.getElementById("name").onkeyup = removeWarning;
document.getElementById("email").onkeyup = removeWarning;
document.getElementById("telephone").onkeyup = removeWarning;
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" placeholder="Name"> <span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" placeholder="Email"> <span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" placeholder="Telephone"> <span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
JSFiddle Version: https://jsfiddle.net/xga2shec/
First of all, we change your function validateForm so it can handle multiple validations.
Then, we create a DOMContentLoaded event handler on the document, and we call the validateForm function, so we validate the field when the page is loaded.
And to finish, we create input event handlers on the inputs, so everytime someone change any data inside them, the form is validated again.
Take a look at the code commented, and see the working version in action!
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
you have to use style.display="none" to hide error
and style.display="block" to show error
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="block";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (x != null || x != "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="none";
return false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="block";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (y != null || y != "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="none";
return false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="block";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else if (z != null || z != "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="none";
return false;
}
else {return true;}
}
</script>
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>

Categories

Resources