Form continues to submit despite custom validation logic - javascript

I have developed some logic to display relevant errors when the form is submitted, but it continues to allow me to submit the form without displaying the errors. I used a flag to determine whether the form should be submitted, but it seems to be ignored, it's just not working.
if (this.formId == "challengeQuestionAuth") {
return new Promise(function (resolve, reject) {
debugOut("Question: " + _this.payload.question, "alert");
let div = document.createElement('div');
div.innerHTML = `
<div id="contentWrapper" style="display: block;">
<div class="page">
<div class="page-body">
<div>
<div class="page-title">Online Banking Security Challenge</div>
<div class="main-section">
<div class="page-instructions">
This action requires you to answer a security question before it can be completed.
</div>
<form class="form" method="post" name="security_challenge" id="security_challenge">
<input type="hidden" />
<div class="validation-summary-valid alert alert-error" data-valmsg-summary="true">
<span>
Please correct the highlighted field(s) below.
</span>
<ul>
<li style="display: none;"></li>
</ul>
</div>
<div class="content-panel">
<fieldset>
<input name="Text" id="Text" type="hidden" value="What is your best friend's middle name?" />
<input name="" id="" type="hidden" value="" />
<div class="challenge-question">
<label for="challengeResponse">
${_this.payload.question}
</label>
</div>
<div class="challenge-answer">
<input aria-required="true" name="challengeResponse" class="control" id="challengeResponse" autofocus="autoFocus" type="password" autocomplete="off">
<span class="error"><p id="answer_error"></p></span>
<input class="checkbox" id="ShowAnswer" type="checkbox">
<label class="label" for="ShowAnswer">Show answer</label>
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Answer"></span>
</div>
<div class="action-group-bottom">
<a id="cancelButton" class="cancel-button contextual-link" href="">Cancel</a>
<input name="Action:SecurityQuestion" id="continueButton" class="primary-action orange-button" type="submit" data-clear-alerts="true" value="Submit" />
</div>
</fieldset>
</div>
</form>
</div>
<div aria-required="true" name="challengeQuestion" type="text" id="challengeQuestion">${_this.payload.question}</div><br />
<label class="control-label" for="challengeResponse">Response:</label>
</div>
</div>
</div>
</div>`;
uiContainer.appendChild(div);
document.getElementById("security_challenge").onsubmit = function() {
const answer = document.forms["security_challenge"]["challengeResponse"].value;
const submit = true;
if (answer == null || answer == "") {
answerError = "Please provide an answer.";
document.getElementById("answer_error").innerHTML = answerError;
submit = false;
}
return submit;
}
Here is a minimally reproducible example:
https://codepen.io/ldco2017/pen/dyMMpjb?editors=0010

I was able to disallow the form to be submitted with what I have below. Adding strict comparison operator to if statement and change const submit to let submit because you are reassigning it.
let submit = true;
if (answer === null || answer === "") {
answerError = "Please provide an answer.";
document.getElementById("answer_error").innerHTML = answerError;
submit = false;
}

Related

Phone Number Regex Validation error while showing/hiding Elements

I am working on a form where I am showing a div when a user submits the form and it checks if all the fields values are not blank. I have achieved that part and it is working fine.
Now the problem is when I am validating the phone number using regex, it is showing error but still displays the div and form is also submitted successfully. It should not get submit till the user enters a correct phone number, it gives an error and still, the form gets submitted. I know the error is there but I am not understanding where I am wrong. Please guide me.
function mySub() {
const user = document.getElementById('pmname').value.trim();
const uemail = document.getElementById('pmemail').value.trim();
const uphone = document.getElementById('pmphone').value.trim();
const uregx = /^[0-9]{10}$/;
const upmmb = uregx.test(uphone);
if (user == "" || uemail == "" || uphone == "" || upmmb == "") {
document.getElementById('agy').style.display = 'none';
alert("Enter Valid Mobile Number");
document.getElementById('pmphone').focus();
} else {
document.getElementById('agy').style.display = 'block';
}
}
#agy {
display: none;
}
<form method="post" action="#">
<div id="agy">
<div class="agent-details">
<div class="d-flex align-items-center">
<div class="agent-image">
<img class="rounded" src="#" alt="Jazz" width="70" height="70" />
</div>
<ul class="agent-information list-unstyled">
<li class="agent-name"><i class="houzez-icon icon-single-neutral mr-1"></i> Jazz</li>
<li class="agent-link">View Listings</li>
</ul>
</div>
</div>
</div>
<div class="form-group">
<input class="form-control" name="name" id="pmname" value="" type="text" placeholder="Name" />
</div>
<div class="form-group">
<input class="form-control" name="mobile" id="pmphone" value="" type="text" placeholder="Phone" />
</div>
<div class="form-group">
<input class="form-control" name="email" id="pmemail" value="" type="email" placeholder="Email" />
</div>
<div class="form-group form-group-textarea">
<textarea class="form-control hz-form-message" name="message" rows="4" placeholder="Message">Hello, I am interested in ...</textarea>
</div>
<div class="form-group">
<label class="control control--checkbox m-0 hz-terms-of-use">
<input type="checkbox" id="ppa" name="privacy_policy" checked="" />By submitting this form I agree to <a target="_blank" href="https://propertymakkerz.com/pm/property/sai-ashishkaranjadepanvel/">Terms of Use</a>
<span class="control__indicator"></span>
</label>
</div>
<div class="form_messages"></div>
<button type="button" class="houzez_agent_property_form btn btn-secondary btn-full-width" onclick="mySub()"><span class="btn-loader houzez-loader-js"></span> Send Message</button>
</form>

Not able to verify if input field is empty or not after clicking the sumbit button

I am basically checking to see if the input field(fullName) is empty or not. If it is empty, then I want to disable the submit button, and forcing the user to add text in the FullName field.
To achieve this scenario, I did the following(code below), but when testing, I am still able to click the submit button, even if the FullName field is empty. I am not sure, what I am doing wrong with the JavaScript code.
I am doing all of this inside an .htm file.
function checkform(form) {
if (form.FullName.value == "") {
alert("Please enter your name!");
form.FullName.focus();
return false;
}
return true;
}
<fieldset>
<div class="form-group">
<label class="" for="FullName">Name <span class="required">*</span></label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
</fieldset>
function checkform(form) {
if (form.FullName.value == "") {
alert("Please enter your name!");
form.FullName.focus();
return false;
} else {
return true;
}
}
<div id="Wrapp" class="container">
<div id="MyName" class="center">
<button id="btn_MyNamebutton" class="btn btn-namebtn">Sign In</button>
<fieldset>
<form name='form' id='form'>
<div class="form-group">
<label class="" for="FullName">Name <span class="required">*</span></label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
<!-- Button -->
<div class="form-group">
<button id="btn_sumbit" type="button" class="btn btn-namebtn" onclick='checkform(form)'>Sign up</button>
<button id="btn_clear" type="reset" class="btn">Cancel</button>
</div>
</form>
</fieldset>
</div>
</div>
Note:- You have not added form tag and onclick='checkform(form)' which created issue in your code.
Your JS is ok. There are some changes -
First, wrap the form content in a form with a name attribute of form.
Next, fire the checkform function on clicking the submit button.
Check the snippet below-
function checkform(form) {
if (form.FullName.value == "") {
alert("Please enter your name!");
form.FullName.focus();
return false;
}
return true;
}
<div id="Wrapp" class="container">
<div id="MyName" class="center">
<button id="btn_MyNamebutton" class="btn btn-namebtn">Sign In</button>
<form name="form">
<fieldset>
<div class="form-group">
<label class="" for="FullName">Name
<span class="required">*</span>
</label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
<!-- Button -->
<div class="form-group">
<button id="btn_sumbit" type="submit" class="btn btn-namebtn" onclick="checkform(document.form)">Sign up</button>
<button id="btn_clear" type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
Is this what you are attempting?
Onclick if value of input is empty then you will see alert and button will disable.
EDIT: Included comments in code.
//get FullName input by id
var FullName = document.getElementById("FullName");
//get button by id
var btn_submit = document.getElementById("btn_submit");
function checkform() {
//if FullName is empty then alert and disable button
if (FullName.value === "") {
alert("Please enter your name!");
btn_submit.disabled = true;
}
}
<div id="Wrapp" class="container">
<div id="MyName" class="center">
<button id="btn_MyNamebutton" class="btn btn-namebtn">Sign In</button>
<fieldset>
<div class="form-group">
<label class="" for="FullName">Name <span class="required">*</span></label>
<input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1">
</div>
<!-- Button -->
<div class="form-group">
<button onclick="checkform();" id="btn_submit" type="submit" class="btn btn-namebtn">Sign up</button>
<button id="btn_clear" type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</div>
</div>

How to call mutiple id using `this` in jquery

here I'm doing contact forms.In the same page, I have 10 forms and I want to validate all form.I want to use same validation code for all forms.here I gave id's but the problem is the same id's not working on the same page.I want to use current id.Can anyone suggest how should I do?
Feel free to tell is there any mistakes in my code.
Thanks
$(document).ready(function(){
/* name*/
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){
input.removeClass("invalid").addClass("valid");
}
else{
input.removeClass("valid").addClass("invalid");
}
});
/* E-mail */
$('#contact_email').on('input', function() {
var input=$(this);
var regex = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var is_email=regex.test(input.val());
if(is_email){
input.removeClass("invalid").addClass("valid");
}
else{
input.removeClass("valid").addClass("invalid");
}
});
/* select People*/
$('#contact_select').change(function() {
var select=$(this);
var selectOption = $("#contact_select option:selected").val();
if(selectOption){
select.removeClass("invalid").addClass("valid");
}
else{
select.removeClass("valid").addClass("invalid");
}
});
/* select Time*/
$('#contact_time').change(function() {
var select=$(this);
var selectTime = $("#contact_time option:selected").val();
if(selectTime){
select.removeClass("invalid").addClass("valid");
}
else{
select.removeClass("valid").addClass("invalid");
}
});
/* Submit */
$("#contact_submit button").click(function(event){
var form_data = $("#contact").serializeArray();
var error_free = true;
for (var input in form_data){
var element = $("#contact_"+form_data[input]['name']);
var valid = element.hasClass("valid");
var error_element = $("span", element.parent());
if (!valid){
error_element.removeClass("error").addClass("error_show");
error_free=false;
}
else{
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free){
return false;
}
else {
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row current" id="demo1">
<form id="contact" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
<div class="row current" id="demo2">
<form id="contact" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="submit" class="btn"> Submit</button>
</div>
</form>
</div>
It seems you are using HTML5, then adding custom methods for validation is not a good idea.
Try using jquery validation and pattern attribute like:
function submitForm(id){
var isValid = $("#" + id).valid();
if(isvalid)
/* Yes valid*/
else
/* Invalid*/
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<div class="row current" id="demo1">
<form id="contact1" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="button" class="btn" onclick="submitForm('contact1')"> Submit</button>
</div>
</form>
</div>
<div class="row current" id="demo2">
<form id="contact2" method="post" action="">
<div class="detail">
<input type="text" id="contact_name" name="name" required autocomplete="off" />
<span class="inputBar"></span><!--inputBar-->
<label for="contact_name">Name</label>
<span class="error">This field is required</span>
</div><!--detail-->
<div class="detail">
<input type="text" id="contact_email" name="email" required autocomplete="off" pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"/>
<span class="inputBar"></span><!--inputBar-->
<label for="contact_email">Email</label>
<span class="error">A valid email address is required</span>
</div><!--detail-->
<div class="btn-container" id="contact_submit">
<button type="button" onclick="submitForm('contact2')" class="btn"> Submit</button>
</div>
</form>
</div>
UPDATE:
Dynamic function called on button clicked. Type is button instead of submit
Hope you will get the point and it helps.
Happy Coding !!!!
You can use a custom attribute like data-validation="validation-type" on your input controls then do a for each on your form with
$('<myform>').find('*[data-validation]').each(function(){
// in here get the this object for each input control the code to validate comes here
var valType = $(this).attr('data-validation');
switch(valType)
{
case 1:
//validation of case 1
break;
//add other cases as of your need.
}
});
Edit 1
For example you can play around with this snippet:
var button = $("button")
// handle click and add class
button.on("click", function() {
//validating controls for form 1
debugger;
$('#myform1').find('*[data-validation]').each(function(e) {
validateInput(this);
});
//validating controls for form 2
$('#myform2').find('*[data-validation]').each(function(e) {
validateInput(this);
});
})
function validateInput(control) {
if (control == null || control === undefined)
return null;
var validType = $(control).attr('data-validation');
if (validType == null || validType === undefined)
return null;
switch (validType) {
case "text":
if ($(control).val().trim().length == 0)
$(control).addClass('invalid').removeClass('valid');
else
$(control).addClass('valid').removeClass('invalid');
break;
case "number":
debugger;
var value = $(control).val().trim();
if (isNaN(value) || value.length == 0)
$(control).addClass('invalid').removeClass('valid');
else
$(control).addClass('valid').removeClass('invalid');
break;
}
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
.valid {
border: 2px solid green;
}
.invalid {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>
Form 1
</h4>
<form id="myform1">
<label>Enter name</label>
<input type="text" data-validation="text" value="">
<br/>
<label>Enter Age</label>
<input type="text" data-validation="number" value="">
<br/>
</form>
<h4>
Form 2
</h4>
<form id="myform2">
<label>Enter name</label>
<input type="text" data-validation="text" value="">
<br/>
<label>Enter Age</label>
<input type="text" data-validation="number" value="">
<br/>
</form>
<button>
Click me to validate
</button>

Submitting form within a function

Probably a very easy fix for you JS gurus out there, currently I have a form with some basic validation. If i call it outside of a submit function it works fine, however i need the form to submit once it checks the validation, can anyone help? Also is the correct way to call it by returning true at the bottom of the function?
function submitForm() {
//Form validation, post.
submitBtn.addEventListener("click", function(event) {
event.preventDefault();
//Form fields
const contactName = document.getElementById("form__contact-name").value;
const contactEmail = document.getElementById("form__contact-email").value;
const contactPhone = document.getElementById("form__contact-phone").value;
const contactMessage = document.getElementById("form__contact-message").value;
//Check if values aren't empty, if they're not post form. Else alert the user to complete.
contactName !== '' && contactEmail !== '' && contactPhone !== '' && contactMessage !== '' ?
true :
alert("Please complete form");
})
}
<form action="#" method="post">
<div class="form__contact-wrapper">
<label for="Your name">Your Name</label>
<input id="form__contact-name" type="text" name="contact-name" />
</div>
<div class="form__contact-wrapper">
<label for="Your email">Your email address</label>
<input id="form__contact-email" type="text" />
</div>
<div class="form__contact-wrapper">
<label for="Your phone number">Your phone number</label>
<input id="form__contact-phone" type="number" />
</div>
<div class="form__contact-wrapper">
<label for="Your message">Your message</label>
<textarea id="form__contact-message" rows="5"></textarea>
</div>
<div class="form__contact-wrapper">
<input id="submitbtn" type="submit" value="send my message" onsubmit="submitForm()" />
</div>
</form>
Use preventDefault() only if the validation doesn't pass.
document.getElementById('contact-form').addEventListener('submit', function(e) {
const contactName = document.getElementById("form__contact-name").value;
const contactEmail = document.getElementById("form__contact-email").value;
const contactPhone = document.getElementById("form__contact-phone").value;
const contactMessage = document.getElementById("form__contact-message").value;
if (contactName === '' || contactEmail === '' || contactPhone === '' || contactMessage === '') {
e.preventDefault();
alert("Please complete form");
}
});
<form action="#" method="post" id="contact-form">
<div class="form__contact-wrapper">
<label for="Your name">Your Name</label>
<input id="form__contact-name" type="text" name="contact-name" />
</div>
<div class="form__contact-wrapper">
<label for="Your email">Your email address</label>
<input id="form__contact-email" type="text" />
</div>
<div class="form__contact-wrapper">
<label for="Your phone number">Your phone number</label>
<input id="form__contact-phone" type="number" />
</div>
<div class="form__contact-wrapper">
<label for="Your message">Your message</label>
<textarea id="form__contact-message" rows="5"></textarea>
</div>
<div class="form__contact-wrapper">
<input type="submit" value="send my message" />
</div>
</form>

How to send localstorage with form

I have html form and localstorage
I need send data from localstorage and form on email
Now I am sending two letter :(
When user submit form I get two letter. First letter from form and second letter from localstorage
So, I want get one letter with localstorage and form
My form:
<form action="/send.php" id="form-cart-send" onsubmit="return sendCartdata();" method="post" enctype="multipart/form-data" required>
<div class="form_fields" data-count="3">
<div class="form_field" data-type="name" data-is-required="true">
<label class="field_title">Имя<i>*</i></label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="name" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="phone" data-is-required="1">
<label class="field_title">Телефон<i>*</i></label>
<div class="form_field_text">
<input type="tel" class="form_field_text_input form_phone" id="phone" name="phone" data-check="phone" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="email" data-is-required="0">
<label class="field_title">Ваш e-mail</label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="email" data-check="email" autocomplete="off" required>
</div>
</div>
</div>
<div class="form_fields_advanced"></div>
<div class="form_submit">
<a class="component-button form_field_submit filled squared" id="checkout" data-modal-id="cart_done">
<div class="btn-content">
<div class="form_submit_text">Заказать</div>
</div>
</a>
</div>
</form>
Script for localstorage:
<script>
function sendCartdata() {
var phone = document.getElementById("phone").value;
if (phone === '') {
alert("Заполните, пожалуйста, обязательные поля.");
return false;
} else {
setTimeout(function() {
var value = localStorage.getItem('cart');
jQuery.post("/cart-send.php", {
cart: value
}, function(data) {
}).fail(function() {
alert("Damn, something broke");
});
}, 100);
return false;
}
}
</script>

Categories

Resources