Valid inputs and use animation untill page load - javascript

I need to validate filled inputs and on submit if all inputs are valid show load animation till next page will shown. I can check for validation one by one, but do not know how to collect them all in one. Maybe there are more simple way to check inputs validation? Also I did all validations inside inputs in code below.
Here is my inputs type which i need to validate and on success show load animation until page refresh to another page:
<form action="" method="POST" enctype="multipart/form-data" name="formz" >
<div>
<label>Name: </label>
<input type="text" onkeydown="return keyDown.call(this,event)" onchange="value = value.replace(/^\s+/,'')" pattern=".{3,20}" name="name" required>
</div>
<div>
<label>Surname: </label>
<input type="text" onkeydown="return keyDown.call(this,event)" onchange="value = value.replace(/^\s+/,'')" pattern=".{3,20}" name="surname" required>
</div>
<div>
<label>Unic Number: </label>
<input type="text" onkeydown="return keyDown.call(this,event)" onchange="value = value.replace(/^\s+/,'')" pattern=".{7,7}" maxlength='7' name="unicnumb" required />
</div>
<div>
<label>Select:</label>
<select name="select" id="select" required>
<OPTION VALUE="0" selected disabled >Select</OPTION>
<OPTION VALUE="1">Select1</OPTION>
<OPTION VALUE="2">Select2</OPTION>
</select>
</div>
<div>
<label>phone: </label>
<input type="text" name="phone" id="phone" placeholder="+XXX(XX) XXX-XX-XX" required>
</div>
<div>
<label for="epoct">E-mail</label>
<input type="email" pattern="[a-zA-Z0-9.-_]{1,}#[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" class="form-control input-sm" name="epoct" id="epoct" required>
</div>
<button type="submit" name="button" id="button">Done</button>
</form>

This is the outline for how I've handled successive form validation with jQuery:
$(document).ready(function() {
$( "#button" ).submit(function( event ) {
if ( /* validation fails for first form element */ ) {
// stop form submission
event.preventDefault();
// display an error message
$( "#firstFormFieldId" ).append("<span>Incorrect entry</span>");
// break out of function to ensure validation continues if and only if this condition is met
return false;
}
if ( /* validation fails for second form element */ ) {
// stop form submission
event.preventDefault();
// display an error message
$( "#secondFormFieldId" ).append("<span>Incorrect entry</span>");
// break out of function to ensure validation continues if and only if this condition is met
return false;
}
if ( /* validation fails for third form element */ ) {
// stop form submission
event.preventDefault();
// display an error message
$( "#thirdFormFieldId" ).append("<span>Incorrect entry</span>");
// break out of function to ensure validation continues if and only if this condition is met
return false;
}
// ... repeat for as many form fields that need validation
// if all validation criteria are met, you can deploy loading animation here :)
/* loading animation goes here */
});
});
You can probably already imagine some variations to this template. For instance, rather than appending the <span>s, you could add empty <span>s intended to contain the error messages to your HTML. If an error message needs to be displayed, you then use jQuery to add the text of the error message to the corresponding <span>. The actual implementation will depend on you, but this style has worked well for me.

Related

How to cut short multiple if else statements in Javascript

I recently came across a situation where I was working on a huge form with atleast 60 fields and I wanted that form to only submit if all fields were filled and if not, I wanted to show a custom message (Sweetalert) for every field not filled.
For example, If first name was left empty, show the message "Please enter your first name", If country of residence was not selected, show them the message that "Please select your country of residence" so on and so forth.
While I was writing tons of if and else statements to match every field using document.getElementById(), this thought of not doing things right came into my mind. I tried searching the web for this but was unable to find a suitable way of doing such things. Can anyone suggest me a better way rather then writing if else statements of 100 lines ?
By adding a specific class to your form controls you'd be able to retrieve them and iterate through them in order to check which ones are not filled.
Let's say this is your form:
<form id="myForm" name="myForm" novalidate>
<div>
<label for="control_1">Label_1:</label>
<input type="text" id="control_1" name="control_1" class="control" />
</div>
<div>
<label for="control_2">Label_2:</label>
<input type="text" id="control_2" name="control_2" class="control" />
</div>
<div>
<label for="control_3">Label_3:</label>
<input type="text" id="control_3" name="control_3" class="control" />
</div>
<div>
<label for="control_4">Label_4:</label>
<select id="control_4" name="control_4" class="control">
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
</select>
</div>
<div>
<input type="submit" value="Submit!" />
</div>
</form>
Then you can use the .control class to retrieve all controls and check them:
function onSubmit(e) {
e.preventDefault();
const controls = document
.getElementById("myForm")
.querySelectorAll(".control");
controls.forEach(control => {
if (!isControlFilled(control)) {
console.log(control.id);
// Do whatever you want with control's id
}
});
}
// This is just for illustrative purposes
// Should be adapted to cover all control types
function isControlFilled(control) {
return control.value ? true : false;
}

OnInvalid html event triggering after Required modifier removed through JS

I have three input fields I am attempting to enforce validity on. Currently, I have them all set as required, but removing the modifier with Javascript on submit if one of them is filled out; essentially, one must fill out at least one, but not none of these fields.
Here is an example of the fields:
jQuery(function ($) {
var $inputs = $('input[name=Input1],input[name=Input2], input[name=Input3]');
$inputs.on('input', function () {
// Set the required property of the other input to false if this input is not empty.
$inputs.not(this).prop('required', $(this).val().length > 0 && $(this).val() != 0)
});
});
jQuery(function ($) {
$("#Input1, #Input2").oninvalid = (function() {
$(this).setCustomValidity("Please enter a valid Input1, Input2, or Input3")
});
});
var Input3default = document.getElementById('Input3')
if (Input3.value.length == 0) Input3.value = "0";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="input-group mb-3">
<form action="" method="get" autocomplete="off">
<div class="row" style="text-align:justify; width: 100%; display:inline">
<div class="">
<label for="text3">Input1:</label>
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" />
</div>
<div class="">
<label for="text4">Input2:</label>
<input type="text" id="Input2" name="Input2" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')"/>
</div>
<div class="">
<label for="text5">Input3:</label>
<input type="text" id="Input3" name="Input3" required placeholder="0" pattern="[0-9]*" onsubmit="Input3default" oninvalid="this.setCustomValidity('Please enter a valid Input3')"/>
</div>
</div>
<p>
<input type="submit" value=" Submit " />
</p>
</form>
</div>
</div>
This seems to work fine if I leave it default; I have Input1 and Input2 empty by default, and Input3 has a value of "0" by default. If I enter Input1 or Input2, my submission goes through just fine. However, the problems begin if I alter Input3.
Problem 1: Any time I enter Inputs 1 and 2 but leave 3 blank, it triggers invalidity; my Input3default never seems to trigger, and it is passed blank and caught by the oninvalid tag.
Problem 2: Along with that, if I do not specify an Input2 along with my Input1 while Input3 is blank, it triggers invalidity on Input2. Using Chrome Debugger, I can see that the Required tag is removed, but my OnInvalid pop-up still comes up no matter what is remedied.
Essentially, I am trying to solve the second problem: When I remove the required html tag from my input, after invalidating another input with a Javascript-enforced default, my inputs refuse to validate on the front end.
I appreciate any advice and conjecture as to why this may be the case, and believe that the two problems are connected.
EDIT: Upon adding an = to my original oninvalid JQuery function, I removed a JS error. It appears that my Input3 default function triggers on pageload, but not on submit; I added an onsubmit function to input3, but am still receiving oninvalid events for input2.
I was able to fix this issue on my own, using the OnInput event.
The setCustomValidity function, when triggered, does not allow a submission while a CustomValidity is set. In order to fix this, I edited my inputs as so:
<input type="text" id="Input1" name="Input1" required oninvalid="this.setCustomValidity('Please enter a valid Input1, Input2, or Input3')" oninput="this.setCustomValidity('')"/>
I still have a few kinks to iron out, but this fixed my main problem in that the validity of an input was not being reset.
I'll leave this answer unaccepted at first to allow others to pitch in.

Multiple form validation with same function

I am using form twice on same page.
HTML Code
<form action="post.php" method="POST" onsubmit="return checkwebform();">
<input id="codetext" maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
It's working fine with one form but when i add same form again then it stop working. The second form start showing error popup alert but even i enter text in form field.
JS Code
function checkwebform()
{
var codecheck = jQuery('#codetext').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
}
How can i make it to validate other forms on page using same function?
As I commented, you can't have more than one element with the same id. It's against HTML specification and jQuery id selector only returns the first one (even if you have multiple).
As if you're using jQuery, I might suggest another approach to accomplish your goal.
First of all, get rid of the codetext id. Then, instead of using inline events (they are considered bad practice, as pointed in the MDN documentation), like you did, you can specify an event handler with jQuery using the .on() method.
Then, in the callback function, you can reference the form itself with $(this) and use the method find() to locate a child with the name codetext.
And, if you call e.preventDefault(), you cancel the form submission.
My suggestion:
HTML form (can repeat as long as you want):
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
JS:
$(document).ready(function() {
//this way, you can create your forms dynamically (don't know if it's the case)
$(document).on("submit", "form", function(e) {
//find the input element of this form with name 'codetext'
var inputCodeText = $(this).find("input[name='codetext']");
if(inputCodeText.val().length != 5) {
alert('Invalid Entry');
e.preventDefault(); //cancel the default behavior (form submit)
return; //exit the function
}
//when reaches here, that's because all validation is fine
showhidediv('div-info');
//the form will be submited here, but if you don't want this never, just move e.preventDefault() from outside that condition to here; return false will do the trick, too
});
});
Working demo: https://jsfiddle.net/mrlew/8kb9rzvv/
Problem, that you will have multiple id codetext.
You need to change your code like that:
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
<form action="post.php" method="POST">
<input maxlength="5" name="codetext" type="text" value="" placeholder="Enter here" />
<input class="button" type="submit" value="SUMBIT" />
</form>
And your JS:
$(document).ready(function(){
$('form').submit(function(){
var codecheck = $(this).find('input[name=codetext]').val();
if(codecheck.length != 5)
{
alert('Invalid Entry');
} else {
showhidediv('div-info');
}
return false;
})
})

Can't submit form with data-live-search as true (Bootstrap-select)

I'm making a issue reporting form with categories and sub categories. The form also requires the user to add their e-mail address (from a list). The list has the data-live-search = true to give them the possibility to search for it in the list.
The form submits if you first start to type in the search field for the e-mail and then selects it, but if you don't write in the search bar and just select it from the list (without typing anything), the form won't submit... This is what the form looks like (a simplified version, but still not working):
<form role="form" name="form" id="form" action="file.php" method="post">
<!-- AUTHOR NAME -->
<div class="form-group" id="form-group-author-name">
<label class="sr-only" for="author-name">Author's name</label>
<input type="text" name="author-name" id="form-author-name" placeholder="Author's name" class="form-control" required>
</div>
<!-- AUTHOR E-MAIL -->
<div class="form-group" id="form-group-author-email">
<select class="selectpicker" name="author-email" id="form-author-email" data-width="100%" title="Author's e-mail" data-live-search="true" required>
<option>email1#example.com</option>
<option>email2#example.com</option>
<option>email3#example.com</option>
<option>email4#example.com</option>
<option>email5#example.com</option>
</select>
<p class="help-block">Search for your e-mail.</p>
</div>
<button type="submit" class="btn">Submit</button>
</form>
I've also tried to add an event listener to the select field and use $("#" + "form-author-email").selectpicker('refresh'); and document.getElementById("form-author-email").value = $("#" + "form-author-email").val(); in case it was because of the field not updateing, but that wasn't working either.
If I use console.log($("#" + "form-author-email").val()); I still get the value selected, so I don't understand what the problem is.
I've figured out the problem. I've added a jQuery validation function (for all input fields) that used e.preventDefault(); and added a error styling-class if the input was empty, which it would always be if they didn't type anything into the search bar. I've add the code below in case anybody has done the same thing:
jQuery(document).ready(function() {
$('.form input[type="text"]').on('focus', function() {
$(this).removeClass('error');
});
$('.form').on('submit', function(e) {
$(this).find('input[type="text"]').each(function(){
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('error');
}
else {
$(this).removeClass('error');
}
});
});
});

Trigger html form submit as if you clicked on button (but without a button)?

If you have a <form> and a <button type='submit'> and you click on the submit button, it will do the default form validation, such as checking whether an <input> is required or not. It would normally say Please fill out this field.
However, if I programmatically submit the form through $("form").submit() for example, it would submit it without performing any checks.
Is there a simpler way to perform the default form validations using native JavaScript? There seems to be only checkValidity() on the form element which return true or false. And if I call the same native function on the input itself, it doesn't really do anything.
Here is a demo code of what I mean:
http://jsfiddle.net/totszwai/yb7arnda/
For those still struggling:
You can use the Constraint validation API - https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
<div id="app">
<form>
<input type="text" required placeholder="name">
<input type="text" required placeholder="email">
</form>
<button id="save">Submit</button>
</div>
const form = document.querySelector("form");
document.getElementById("save").addEventListener("click", e => {
e.preventDefault();
if (form.checkValidity()) {
console.log("submit ...");
} else {
form.reportValidity();
}
});
Check out and play here: https://stackblitz.com/edit/js-t1vhdn?file=index.js
I hope it helps or gives you ideas. :)
I think this might be the answer you are looking for :
JavaScript :
document
.getElementById('button')
.addEventListener("click",function(e) {
document.getElementById('myForm').validate();
});
HTML :
<form id="myForm" >
First name: <input type="text" name="FirstName" required><br>
Last name: <input type="text" name="LastName" required><br>
<button id="button">Trigger Form Submit</button>
</form>
Demo : http://jsfiddle.net/2ahLcd4d/2/

Categories

Resources