How to call form validity event if no input is entered - javascript

I have a simple form with bootstrap which I need to validate before submitting. It has auto support for invalid-feedback. It looks like this
let forms = document.querySelectorAll(".needs-validation");
var productNameField = document.getElementById("productName");
productNameField.addEventListener("input", function () {
var val = document.getElementById("productName").value;
console.log("not entering here if I don't enter an input", val);
if (!isValidString(val)) {
productNameField.setCustomValidity("invalid");
} else {
productNameField.setCustomValidity("");
}
});
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
console.log("not valid");
event.preventDefault();
event.stopPropagation();
}
console.log("here validation");
form.classList.add("was-validated");
},
false
);
});
<form
action="/products/addProduct"
enctype="multipart/form-data"
class="needs-validation"
novalidate
method="post"
>
<div class="col-md-12 position-relative">
<label for="productName" class="form-label"
>Product Name</label
>
<input
type="text"
name="productName"
id="productName"
class="form-control"
/>
<div class="invalid-feedback">
Please provide a valid Product Name(at least two
characters, no special characters allowed).
</div>
</div>
<div>
<button type="submit" id="savebutton" name="Submit">
Create
</button>
</div>
</form>
Now when I type an input I immediately see an error if !validString (because of the input eventlistener). But if I just click on the submit button it is not calling the validString function.
What should I do ?

const productNameField = document.getElementById("productName");
const isInputValid = function() {
return productNameField.value.length > 1;
}
const updateValidity = function() {
if (isInputValid()) {
productNameField.classList.remove('invalid')
} else {
productNameField.classList.add('invalid')
}
}
productNameField.addEventListener("input", updateValidity);
const forms = document.querySelectorAll(".needs-validation");
Array.prototype.slice.call(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
updateValidity();
if (isInputValid()) {
console.log("validation complete");
form.classList.add("was-validated");
} else {
console.log("validation failed");
event.preventDefault();
}
}
);
});

Related

ValidateForm How to validate and show text when submit button was clicked in JavaScript

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>

recheck password character by character while typing

I'm working on recheck password while typing.Can anyone help me with the code that checks while typing password that shows a notification if it doesn't match entirely character by character while typing and that checks the length too when submit button is pressed in jquery or javascript
You can do this by several ways. This DEMO will solve your problem by using Jquery validation.
HTML
<form class="validatedForm" id="commentForm" method="get" action="">
<fieldset>
<input name="user[password]" id="user_password" required/><br>
<input name="user[password_confirmation]" required/>
</fieldset>
</form>
<button>Validate</button>
JQuery
jQuery('.validatedForm').validate({
rules: {
"user[password]": {
minlength: 3
},
"user[password_confirmation]": {
minlength: 3,
equalTo : "#user_password"
}
}
});
$('button').click(function () {
console.log($('.validatedForm').valid());
});
Original answer - https://stackoverflow.com/a/9717644/7643022
That answer gives you the solution to what you need. I have just modified the answer to what you desire.
html
<div class="td">
<input type="password" id="txtNewPassword" />
</div>
<div class="td">
<input type="password" id="txtConfirmPassword" onChange = "checkPasswordMatch();" />
</div>
<div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>
<div><input type="submit" id="submitbtn"/></div>
JQuery
var incorrectFlag = false;
function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword)
incorrectFlag = true;
else
incorrectFlag = false;
}
$(document).ready(function () {
$("#txtConfirmPassword").keyup(checkPasswordMatch);
$("#submitbtn").onclick(function(e){
e.preventDefault();
if (incorrectFlag){
alert("Password Incorrect");
} else {
$('form').submit();
}
});
});
The Actual password should be retrieved and stored somewhere, here I assumed it should be stored in the hidden input.
$(document.ready(
var actual_password = $("#hidden_input_password").val();
$( "#password_text_box" ).keyup(function(event) {
var input_Password = $(this).val();
if(input_Password.length > actual_password.length)
{
event.preventDefault();
event.stopPropogation();
return;
}
elseif(input_Password.length === actual_password.length){
if(input_Password===actual_password)
{
return;
}
else{
event.preventDefault();
event.stopPropogation();
$(this).addClass("notification");
return;
}
}
else{
if(input_Password!===actual_password.slice(0,input_Password.length))
{
event.preventDefault();
event.stopPropogation();
$(this).addClass("notification");
return;
}
}
});
);

OnBlur Validation Requires Onsubmit Button to Be Clicked Twice in Pure Javascript

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>

Show <div> when e-mail is validated Jquery

I would like to show my div when the email isn't validated. And hide it when it is.
This is what I tried, but it isn't working.
$("#fes-email").on("change.validation keyup.validation", function () {
var email = $(this).val();
$("#fes-submit").prop("disabled", email.length == 0 || !isValidEmailAddress(email));
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled')
$("#notification-container").show("slide");
});
}).trigger('change.validation');
You exit the function before you show it.
$('#fes-form').submit(function () {
return !$("#fes-submit").is(':disabled') <---exits function
$("#notification-container").show("slide"); <-- will never be called
});
AND you have a BIGGER problem. On every single change you are binding a submit handler to the form. That is BAD. Take the submit handler OUT of the change event.
(function() {
var isValid = false;
$("#fes-email").on("change.validation keyup.validation", function() {
var email = $(this).val();
isValid = email.length && isValidEmailAddress(email);
}).trigger('change.validation');
$('#fes-form').submit(function() {
if (isValid) {
$("#notification-container").slideUp();
} else {
$("#notification-container").slideDown();
}
return isValid;
});
}());
function isValidEmailAddress(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
#notification-container {
background-color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="fes-form">
<label for="fes-email">Email</label>
<input type="text" id="fes-email" name="fes-email" class="validation" />
<input type="submit" />
</form>
<div id="notification-container">Invalid Email</div>

Confirmation dialog

I like to add confirmation dialog. like"confirm adding (the amount)?" if yes it will proceed to addcontribution.php and if no it will go back to itself and reset the field.
<form form="CONTRIFORM" name='contribution' method="POST" Action="addcontribution.php" onSubmit="return formvalidation2();">
<center>
Amount:
<input type="text" name="contriamnt" id="contriamnt" size="15" placeholder=" Amount"></br></br>
<button id="searchbutton" type="submit" name="submit" value="Submit">ADD</button></br>
</center>
</form>
<script>
function formvalidation2() {
var amntDATA = document.contribution.contriamnt;
if(allnumber(amntDATA)) {
if(ChangeText()) {
if(new_tab()) {
}
}
}
return false;
}
function allnumber(amntDATA) {
var x = /^[0-9]+$/;
if(amntDATA.value.match(x)) {
return true;
} else {
alert('Invalid Amount.');
return false;
}
}
</script>
Example
if (confirm('Confirm Adding (the amount)?')){
window.location = "http://www.google.com/"; // your Custom Link
}else{
document.getElementById('contriamnt').value="";
}

Categories