I have a form which validates password null/blank or not using onblur. And I use a submit button to submit the form. However the submit button needs to be clicked twice before to work. It does not work on the first click after something has been filled in the password box. Below is the code.
With respect to Jquery, I require solution in pure Javascript.
I have tried onkeyup, but that is not a good solution as it will put strain on system, and server (for ajax).
<!DOCTYPE html>
<html>
<body>
<script>
var error_user_password = false;
function checkpw(){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall() {
checkpw()
if(error_user_password == false) {
return false;
} else {
return true
}
}
</script>
</body>
<form id="joinform" method="post" name="joinform" action="#hello" onsubmit="return submitall()" >
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password" onblur="checkpw()" />
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
</html>
OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript
This happens because the blur event is captured from the onblur event handler and not bubbled to the form submit button.
A full javaScript solution is based on:
addEventListener
activeElement: inside the blur event I check after 10 milliseconds if the submit button get the focus.
My snippet:
var error_user_password = false;
function checkpw(ele, e){
var user_password = document.forms["joinform"]["user_password"].value;
if (user_password == null || user_password == "") {
text = "Password : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_password = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_password = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_password == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_password').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="password" name="user_password" id="user_password" placeholder="Password"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>
Related
I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
HTML
I have some simple html input here and I would like to put it in a POST form
<form method="POST">
{% csrf_token %}
<input type="text" id="myTextInputID" placeholder=" Your amazon URL">
</form>
JAVASCRIPT
function search(){
var inputValue = document.getElementById("myTextInputID").value;
}
document.getElementById("myTextInputID").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
var input = document.getElementById("myTextInputID").value;
document.getElementById(search());
var error = document.getElementById("error")
if (input.includes("https://www.amazon.co.uk/")){
error.style.display = "none";
}else{
error.style.display = "block";
setTimeout(function(){error.style.display = "none";} ,2000)
}
}
});
function togglePopup(){
document.getElementById("popupe-1").classList.toggle("active");
}
And I have my if function here when I don't have my user input as a post method it works perfectly fine, but when I add the post method the page just reloads each time and doesn't run my javascript function
It because when user presses Enter, it triggers the form submit action, and it will reload the page.
To prevent form submit action to be triggers, add onkeydown="return event.key != 'Enter';" to your form.
function search(){
var inputValue = document.getElementById("myTextInputID").value;
}
document.getElementById("myTextInputID").addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
var input = document.getElementById("myTextInputID").value;
document.getElementById(search());
var error = document.getElementById("error")
if (input.includes("https://www.amazon.co.uk/")){
error.style.display = "none";
}else{
error.style.display = "block";
setTimeout(function(){error.style.display = "none";} ,2000)
}
}
});
function togglePopup(){
document.getElementById("popupe-1").classList.toggle("active");
}
<form action="https://www.google.com" method="POST" onkeydown="return event.key != 'Enter';">
<input type="text" id="myTextInputID" value="https://www.amazon.co.uk/" />
</form>
<div id="popupe-1">Helloworld</div>
<div id="error">I'm a error</div>
I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>
$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode === 13){
SearchThis.submit();
return false;
}
});
});
So now my form (SearchThis) is submitted whenever the enter key is pressed which is great however how do I modify it to check if mysearchfied has been completed before it submits?
IE. If mysearchfied is empty and the enter key is pressed don't submit the form. If mysearchfied contains text and the enter key is pressed then submit the form.
Hope you can help! Thanks...
If you just want to validate the textbox for required use HTML5 required attribute like:
<input type="text" class="form-control" name="mysearchfield"
value="" id="mysearchfield" placeholder="Company or SmartPages Category..." autocomplete="off" required>
listenOn = function(domElement) {
domElement.addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
onEnterPressed();
}
});
function onEnterPressed() {
if (validateForm()) {
submitForm();
} else {
alert('Invalid form');
}
}
function validateForm() {
var inputValue = document.getElementById("myInput").value;
return (inputValue.length >= 1);
}
function submitForm() {
var formElement = document.getElementById("myForm");
alert('Submit form');
formElement.submit();
}
}
listenOn(document);
//listenOn(document.getElementById("myForm")); //You could also listen keydowns on form element(sure only if global keypress isn't exactly what you want).
<form id="myForm" action="#send.php">
<input id="myInput" type="text" placeholder="I'm empty now." />
</form>
There are two ways to validate the form.
-> Check is the form valid usind the form valid function
SearchThis.validate().valid()
-> validate each field for value as told by #n01ze
if the id of your input field is mysearchfield, then you could do it like this:
var msf = document.getElementById("mysearchfield").value;
$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode == 13){
if (msf != "") {
SearchThis.submit();
return false;
}
else
{
// some code here....
}
}
});
});
if (event.keyCode === 13) {
if ($('mysearchfied_ID_or_Class').val()!=='') {
//mysearchfied is not empty
SearchThis.submit();
}
else {
//dont submit, do your checks
}
return false;
}
I'm trying to submit a HTML form, only when all the fields do not return false in the Javascript code.
My HTML looks like this, for simplicity I have just kept the name and email
<form method="post" action="RegistrationServlet" class="iform"
onsubmit="return sendForm();">
<ul><li><label for="YourName">*Your Name <span id="regNameErr"></span></label>
<input class="itext" type="text" name="YourName" id="YourName" /></li>
<li><br /><label for="YourEmail">*Your Email <span id="regEmailErr"></span></label>
<input class="itext" type="text" name="YourEmail" id="YourEmail" /></li>
<li><input type="submit" value="Submit" class="ibutton" name="SendaMessage"
id="SendaMessage" value="Send a Message!" readonly="readonly" /></li></ul></form>
The Javascript looks like this, again for simplicity I am just checking 2 fields:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
window.sendForm = function() {
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
$("#YourName").addClass("required");
window.scroll(0, 190);
$("#regNameErr").text("required");
return false;
}
if ($("#YourEmail").val() == "") {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
if (!isEmailValid($("#YourEmail").val())) {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Why is the sendForm() function not repeatedly being called to check that all fields are correct before submitting. Any ideas?
Also I understand that I can add a bounty after 2 days but I am not seeing any button on the editor.
Can you help?
sendForm is called only once per submit - this how it works, and there is no reason to call it multiple times.
If you want to have all your fields checked on submit - you should not return after each check. Instead you should postpone this action until the all fields are verified, and introduce some flag to remember results:
function() {
var formValid = true;
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
...
formValid = false;
}
if ($("#YourEmail").val() == "") {
...
formValid = false;
}
if (!isEmailValid($("#YourEmail").val())) {
...
formValid = false;
}
if (!formValid) {
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Side note. Have you considered any jQuery validation plugins for this? Might save you some implementation and maintenance efforts.