custom web component with vanilla javascript and validations - javascript

I am working in a web component, but I want to add it validations with javascript constrains, but It looks like this just work for inputs elements and my main container is a div.
I am not sure if it exists some workaround for this. I had tried to use an input with display none or size 0x0, but this dislike to me and does not work good.
<form action="">
<input type="text" required="" name="field1">
<input type="text" required="" name="field2">
<div name="mycustominput" myValidation="true">
<!--
children html elements render list and another things
I want to validate this with the form
-->
</div>
</form>
Can you help me?

if you try some inputs validate together like this:
<form id="passwordForm" novalidate>
<fieldset>
<legend>Change Your Password</legend>
<ul>
<li>
<label for="password1">Password 1:</label>
<input type="password" required id="password1" />
</li>
<li>
<label for="password2">Password 2:</label>
<input type="password" required id="password2" />
</li>
</ul>
<input type="submit" />
</fieldset>
js
var password1 = document.getElementById('password1');
var password2 = document.getElementById('password2');
var checkPasswordValidity = function() {
if (password1.value != password2.value) {
password1.setCustomValidity('Passwords must match.');
} else {
password1.setCustomValidity('');
}
};
password1.addEventListener('change', checkPasswordValidity, false);
password2.addEventListener('change', checkPasswordValidity, false);
var form = document.getElementById('passwordForm');
form.addEventListener('submit', function() {
checkPasswordValidity();
if (!this.checkValidity()) {
event.preventDefault();
//Implement you own means of displaying error messages to the user here.
password1.focus();
}
}, false);
this link (http://www.html5rocks.com/en/tutorials/forms/constraintvalidation/) is yours.
have a good day.

Related

Use javascript with POST method

sorry for that, but I need your help on something :
I need to get my values in javascript, as it was filled in my form, and I have no clue how to do it, as whenever I tried to search, it was made for people with at least some understanding of javascript. I have none, but tried my best, the results of my efforts are here :
function validateForm() {
var x = form.('form').elements["sexe"];
if (x == null) {
alert("Un sexe doit être sélectionné");
return false;
}
}
I need to get it done by POST method, as get isn't allowed :
<form action="Monformulairedereferencement." method="post" id="sexe" name="form">
<div id="BlueBorder1">
sexe
<input type="radio" id="Homme" name="sexe" value="Homme" aria-checked="true">
<label for="Homme">Homme</label>
<input type="radio" id="Femme" name="sexe" value="Femme" aria-checked="true">
<label for="Femme">Femme</label>
<input type="radio" id="Autre" name="sexe" value="Autre" aria-checked="true">
<label for="Autre">Autre</label>
</div>
<div>
<label for="civilite">civilite</label>
<select name="civilite" id="civilite">
<option value="M.">M.</option>
<option value="Mme.">Mme.</option>
</select>
</div>
<div>
<label for="nom">nom</label>
<input type="text" id="nom" name="nom" minlength="2">
</div>
<div id="BlueBorder2">
<label for="email">email</label>
<input type="email" id="email">
</div>
<div>
<label for="telephone">telephone</label>
<input type="tel" id="telephone" name="telephone">
</div>
<div>
<label for="website">website</label>
<input type="url" name="website" id="website">
</div>
<div id="BlueBorder3">
<label for="datedenaissance">date de naissance</label>
<input type="date" id="datedenaissance" name="date de naissance">
</div>
<div>
hobbies
<input type="checkbox" id="Jeuxvideo" name="hobbies">
<label for="Jeuxvideo">Jeux video</label>
<input type="checkbox" id="Cinema" name="hobbies">
<label for="Cinema">Cinema</label>
<input type="checkbox" id="Lecture" name="hobbies">
<label for="Lecture">Lecture</label>
<input type="checkbox" id="Sport" name="hobbies">
<label for="Sport">Sport</label>
<input type="checkbox" id="Informatique" name="hobbies">
<label for="Informatique">Informatique</label>
</div>
<input id="token" name="token" type="hidden" value="my first website">
<div>
<label for="validation">validation</label>
<input type="submit" value="Envoyer le formulaire" id="validation">
If you have any clue of what isn't working or anything, then I'll gladly accept it. My only goal is to improve and I'm currently very bad.
Have a nice day and thanks for passing by :)
To get a value of a text input in JS, you need to get this input then get its value.
So for example: <input type="text" id="nom" name="nom" minlength="2">
to get this input value in JS, you have to follow 2 steps:
Assign the input element to variable -> let nom = document.getElementById('nom');
Get the value of this input element -> let nomValue = nom.value;
The previous approach can be applied to any text input (text, password, email, ...), textarea, & select menu
For checkboxes or radio buttons, you need to check if they are checked or not, for example: <input type="radio" id="Homme" name="sexe" value="Homme" > to check this, follow 2 steps:
Assign checkbox or radio button to a variable -> let Homme = document.getElementById('Homme');
Check if this checkbox or radio button is checked -> if (Homme.checked) {console.log('Checked')} else {console.log('Checked')}
For simple validation approach for your code, follow this snippet:
<!-- HTML Form -->
<form action="x.php" method="post" id="sexe" name="form">
<input type="text" id="nom" name="nom" minlength="2">
<input type="radio" id="Homme" name="sexe" value="Homme">
<input type="submit" value='Send' >
</form>
<!-- Validation Script -->
<script>
// Get Form Itself
let myForm = document.getElementById('sexe');
// Add Event To Form On Submit, Trigger The Validation Funcntion
myForm.addEventListener('submit', validateForm)
// Validate Form Function
function validateForm(e) {
// Get All Inputs In Your Form
let nom = document.getElementById('nom'); // Text Input
let Homme = document.getElementById('Homme'); // Radio Input
// Check Text Input Value If Not Empty
if(nom.value === '') {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Name Can Not Be Empty');
}
// Check If Radio Button Not Checked
else if (!Homme.checked) {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Radio Button Is Required');
}
// If The Previous Two Validation Steps Is Done And No Errors, The Form Will Be Sent
}
</script>
In my view, the easiest way to grab the value from the form is to use addEventListners with Submit event. It looks likes an element.addEventListner('submit',function);
var forms = document.getElementsByTagName('form'); //we have selected whole form
function formSubmitted(){
const emails = document.getElementsById('email');//select the email section
let emailValue = emails.value // it will give you the value of email after submitting
}
forms.addEventListner('submit',formSubmitted);//eventlistern which run after submiting the data in form

Simple use of the 'required' attribute but also validate the form (to exclude '#')

I’m trying to create a form that ensures the name input field excludes the ‘#‘ symbol but also has the same box appear prompting the user to fill in the field if empty. I assume the box may differ per browser.
To explain my demo further, see this default form:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button type="submit" value="Subscribe">submit</button> <!-- WITH input type submit -->
</div>
</form>
Clicking the submit button will only submit if all fields are completed, but it won’t check if the name field includes an ‘#‘. I can’t edit it to only submit if the field doesn’t include an ‘#‘.
But this demo:
<form id='form-id' action="/" method="post">
<div class="subscribe-form">
<div class="form-section">
<div>
<input type="text" name="first_name" placeholder="name here" id="name-id" required />
</div>
<div>
<input type="text" name="email" placeholder="Email*" id="email-id" required />
</div>
<input id='checkbox-id' type="checkbox" required /> *check here
</div>
<button onclick="checkName()" type="button" value="Subscribe">submit</button> <!-- changed from input type submit -->
</div>
<script>
let form = document.getElementById('form-id'),
ecsName = document.getElementById('name-id'),
ecsEmail = document.getElementById('email-id'),
ecsCheckbox = document.getElementById('checkbox-id');
function checkName() {
let name = ecsName.value,
email = ecsEmail.value;
if(name.includes('#')) {
alert('includes #');
} else if (name == '' || email == '') {
alert('please fill in your details');
} else if (ecsCheckbox.checked == false) {
alert ('unckeded');
} else {
form.submit();
}
}
</script>
</form>
Includes javascript that ensures all fields are completed, but I don’t like the alert and want the same prompt box to appear as with the former form.
Is there any way of doing this? I’m essentially trying to not tamper with the form and let the default settings do most of the work if possible. Also, another quick question - should required be required='required'? Thanks for any help here.

how to do html form vaildation in jquery

i am using html and jquery to do some form vaildations
for ex if user click on a field and doesn't enter any thing, than he clicks on different field... i want to turn field border to red. this way user will know that he can not skip this field...
also when user clicks on button submit, than i also want to do this same, if field is empty than turn border to red
below is what i have so far, is there a better way to do this? bbc it seem like i am repeating alot of same code
on up side it does work fine, so guess i can just keep on repeating code
note i have like 20+ fields so jquery function will be long
forgot to tell that i am using asp fields:
<asp:TextBox ID="FirstNameCTB" ClientIDMode="Static" class="input form-control input-md" runat="server"></asp:TextBox>
javascript code:
<script type="text/javascript">
$(function () {
$('#FirstNameCTB').blur('input', function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '')
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
});
$('#LastNameCTB').blur('input', function () {
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '')
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
else
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
});
$('.CHECKOUTLBC').click(function () {
if ($('#<%=FirstNameCTB.ClientID%>').val().trim() == '') {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=FirstNameCTB.ClientID%>').css('border-color', '');
}
if ($('#<%=LastNameCTB.ClientID%>').val().trim() == '') {
$('#<%=LastNameCTB.ClientID%>').css('border-color', 'red');
return false; // dont go to server side
} else {
$('#<%=LastNameCTB.ClientID%>').css('border-color', '');
}
});
});
</script>
https://jqueryvalidation.org/ can be your solution.
Also here's the examples.
https://jqueryvalidation.org/files/demo/
This plugin has, red border, submit control etc.
Also this plugin will be good.
http://www.formvalidator.net/#reg-form
$.validate({
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
// Restrict presentation length
$('#presentation').restrictLength( $('#pres-max-length') );
<form action="" id="registration-form">
<p>
E-mail
<input name="email" data-validation="email">
</p>
<p>
User name
<input name="user" data-validation="length alphanumeric"
data-validation-length="3-12"
data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)">
</p>
<p>
Password
<input name="pass_confirmation" data-validation="strength"
data-validation-strength="2">
</p>
<p>
Repeat password
<input name="pass" data-validation="confirmation">
</p>
<p>
Birth date
<input name="birth" data-validation="birthdate"
data-validation-help="yyyy-mm-dd">
</p>
<p>
Country
<input name="country" id="country" data-validation="country">
</p>
<p>
Profile image
<input name="image" type="file" data-validation="mime size required"
data-validation-allowing="jpg, png"
data-validation-max-size="300kb"
data-validation-error-msg-required="No image selected">
</p>
<p>
User Presentation (<span id="pres-max-length">100</span> characters left)
<textarea name="presentation" id="presentation"></textarea>
</p>
<p>
<input type="checkbox" data-validation="required"
data-validation-error-msg="You have to agree to our terms">
I agree to the terms of service
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
Assuming all your form inputs are called input, you could loop through them and apply the function with something similar to this.
var inputs = document.getElementsByTagName('input');
for(n = 0; n < inputs.length; n++){
$(function () {
inputs[n].blur('input', function () {
if (inputs[n].val().trim() == '')
inputs[n].css('border-color', 'red');
else
inputs[n].css('border-color', '');
});
});
}
couple things:
issue maybe be that javascript is beeing run before the controls
you should not mix core javascript with jquery libary
you do not need loop when using blur, on, click, etc jquery functions
keeping all those above things in mind, below is a better solutions. works for me
$(function () {
$(".input").blur(function () {
if ($(this).val().trim() == '')
$(this).css('border-color', 'red');
else
$(this).css('border-color', '');
});
});
Have a look at this example below.
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required>
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url">
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
<script>
$("#commentForm").validate();
</script>
Have a look at this example:

Validating messages before submit

I'm making a html5 application which require all fields to be filled in before the submit button can be clicked.
What I want to do now is give an alert if a textbox is not filled in, the problem is that my submit button is disabled until all fields are filled in, so I can't really add an alert to that button.
Any idea's on how to solve this?
I want it so that after filling in the final textbox the submit button becomes available without first having to click on it.
Note that the 'required' does not work.
I have the following code:
HTML:
<form id="winForm">
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
</p>
<p>
<input type="text" id="telefon" name="telefon" onclick="generateFullAdress()" required />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="sendTheMail()" value=" ">
</button><div id="loading"><img src="images/loadingBar.gif" id="load"></img></div>
</p>
</form>
Jquery/JS
<script type="text/javascript">
function generateFullAdress() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
var $input = $('input:text'),
$register = $('#submitBtn');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
if(trigger) {
$register.attr('disabled',true);
}else {
$register.removeAttr('disabled');
}
});
</script>
Help would greatly be appreciated.
Thanks!
If you have a form as such:
<form id="form">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$(function() {
$('#form').submit(function() {
// DO STUFF
return true; // return false to cancel form action
});
});
OR
perform the samething with the onsubmit event like
<form action="youraction" onsubmit="validatefunction" method="post">

jQuery, submit() with multiple forms using .each()

First off, I realize this is not an optimal solution, but the actual production environment is a product of a drunken orgy involving Magento and a lot of cheap plugins, so don't judge me too harshly. I can't be held responsible for other peoples' messes.
I'm trying to submit multiple forms from one page using jQuery. It works fine in IE and FF. Page has four forms, which I loop through them in JS to see if their checkbox is checked and then submit them one by one, using .each() and .submit(). In Chrome, jQuery(this).submit() does not fire until after you have completely exited the function, and then it only actually submits the last form.
Uses jQuery 1.8.1. The working mockup is here
The code follows:
<!DOCTYPE html>
<html>
<head>
<title>asdfad</title>
<script type="text/javascript" src=http://code.jquery.com/jquery-1.8.1.min.js"></script>
</head>
<body class=" listraknewsletter-index-index">
<form id="form4" method="post" class="signup-form"
action="http://www.example.com/action1"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue1"/>
<label for="checkbox">newsletter 1</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form2" method="post" class="signup-form"
action="http://www.example.com/action2"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue2"/>
<label for="checkbox">newsletter 2</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form3" method="post" class="signup-form"
action="http://www.example.com/action3"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue3"/>
<label for="checkbox">newsletter 3</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<form id="form1" method="post" class="signup-form"
action="http://www.example.com/action4"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue4"/>
<label for="checkbox">newsletter 4</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<!-- Area for entering in information -->
<form method="post" action="/">
<label for="email">email</label>
<input type="text" id = "nl_email" name="email"
size="40" maxlength="100" value = ""/>
<label for="name">name</label>
<input type="text" name="name" id = "nl_name" maxlength="50" size="40" value=""/>
<input type="button" value="Subscribe" onclick="processSignups();" />
<script type="text/javascript">
// requires jQuery
jQuery.noConflict();
function processSignups() {
// make sure you have a valid email and name
// make sure email is at least not null
// this is not a pretty regex for sure lol,
// but tis' RFC 2822 valid
var nl_email = jQuery('input#nl_email').val();
var re = new RegExp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
if (re.test(nl_email) == false) {
alert('Please enter a valid email');
return false;
}
// name is not null
if (jQuery('input#nl_name').val() == '') {
alert('Please enter your name');
return false;
}
// make sure at least one checkbox is selected
var checkboxes = jQuery('input.signup-checkbox');
var atLeastOne = false;
jQuery(checkboxes).each(function() {
if (jQuery(this).is(':checked')) {
atLeastOne = true;
}
});
if (atLeastOne == false) {
alert('Please select at least one newsletter checkbox');
return false;
}
// select your forms by class
// var forms = jQuery('form.signup-form');
// for each form
var formIds = new Array();
jQuery('form.signup-form').each(function(index) {
// get the checkbox
var checkbox;
checkbox = jQuery(this).children('input.signup-checkbox');
// if it is checked
if (jQuery(checkbox).is(':checked')) {
// add a hidden field to the form to hold the email
jQuery(this).append('<input type="hidden" name="email" value="' + nl_email + '" />');
// and submit form
jQuery(this).submit();
}
});
// might as well clear the email and name inputs
jQuery('input#nl_name').val('');
jQuery('input#nl_email').val('');
// return false;
}
</script>
</form>
</body>
</html>
Chrome doesn't treat target="_blank" like the other browsers. Try _tab, or dynamically changing them $(this).attr('target', '_'+$(this).attr('id'));

Categories

Resources