I am using html 5 form validation for validate my form before submit, if is valid, submit, but I need validate my User Register form, so it need validate if Password Confirm value is equal camp Password, below is my form example:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
or in jsfiddle
How to can I create my custom validation for work like default validations?
Well you can use JQuery and attach an attribute to be selected for the passwords to validate each other via input event. Use setCustomValidity() to set the message of the input affected to override the default message when the form is submitted.
See the updated fiddle.
As you can see in the fiddle, all you have to do is add an attribute data-equal-id wherein the attribute value must be the ID of password input element to be tested.
HTML
<h1>How to create html5 validation for password confirm?</h1>
<hr>
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf" data-equal-id="pass" /><br/>
<input type="submit"/>
</form>
Javascript
$('[data-equal-id]').bind('input', function() {
var to_confirm = $(this);
var to_equal = $('#' + to_confirm.data('equalId'));
if(to_confirm.val() != to_equal.val())
this.setCustomValidity('Password must be equal');
else
this.setCustomValidity('');
});
you could try putting this code in your header:
<script>
document.getElementById('myform').onsubmit = function() {
if(!validateForm()){ // call your validation function
alert('fail!'); // remove this
return false; // prevent the form to submit
}
}
// your validation function
// compares that the passwords are equal
function validateForm(){
var pass = document.getElementById('pass').value;
var pass_conf = document.getElementById('pass_conf').value;
if(pass == pass_conf){
return true;
}else{
return false;
}
}
</script>
also put the id 'myform' to your form (or the name you want, but change it in the first line)
How about something fun like this using jQuery?
$('input[type="password"]').keyup(function() {
var pass=$('#pass').val();
var conf=$('#pass_conf').val();
if (pass == conf)
$('input[type="submit"]').removeAttr('disabled');
else
$('input[type="submit"]').attr('disabled', 'disabled');
});
The breakdown...
I am keying off of the keyup, so every time a key is pressed in the
password fields the function will fire.
I'm grabbing the value of both password fields, and comparing them.
If the values are the same, I'm enabling the submit button.
If the values are different, I'm disabling the submit button.
Pretty simple, but it works. Here is a demo: http://codepen.io/anon/pen/GxAyC/
(note - I added a couple of other visual enhancements to the demo to show what can be done)
You're using HTML5 for client-side form validation and wish to validate your form prior to form submission. Your form consists of three inputs and your only validation criteria is that both password fields match.
The most simple way to do this is to write a custom submit handler script:
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass === form.pass_conf) {
form.submit();
}
}
Above preventDefault() stops the default form submission behavior so you can execute your check. Then check if the value of the two password fields are equal. And if they are, continue form submission.
To use, attach the custom handler to your form by listening to the submit event:
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
Applied in context to example form provided:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass.value === form.pass_conf.value) {
form.submit();
}
}
</script>
Related
Problem: I'm doing a form to be filled by the user. Once the user clicks submit, if there is an error in the form, it will show an alert. However, when the user clicks "ok" the form will reset all the fields that have been filled so the user needs to repeat in fill in the form all over again.
Question: How to fix this so that when the user clicks "ok" the data is still there?
To stop the page from re-loading add return false; after alert statement, it stops the default action from taking place from the form submit.
alert("Please fill in all mandatory fields");
return false;
You should reset form:
document.getElementById("formId").reset();
The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
Use <button type="button"> to override default submission behavior.
Use event.preventDefault() in the onSubmit event to prevent form
submission.
var form = document.getElementById("myForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('onSubmit', handleForm);
I have something that does exactly that. It's a complete working code, but I am going to give you the task of figuring out which part does what.
function submitInfo(e){
var fields = document.getElementsByClassName('input-field').length;
for(let x = 0; x < fields; x++){
var value = document.getElementById(x).value;
if(value == ''){
e.preventDefault();
var element = document.getElementById(x);
element.classList.add('no-value');
setTimeout(function(){
element.classList.remove('no-value')
},3000);
break;
}
}
}
.no-value {
border: 2px solid red;
}
<form method="post" action="">
<input type="text" name="email" placeholder="Email" class="input-field" id="0"/><br/>
<input type="password" name="password" placeholder="Password" class="input-field" id="1"/><br/>
<input type="submit" value="Submit" onclick="submitInfo(event)"/>
</form>
I hope this is what you are looking for.
I have a common event handler for form submit
handleSubmit = (e) => {
e.preventDefault();
const errors = this.validate();
this.setState({ errors: errors || {} });
if (errors) return;
this.doSubmit();
};
It will handle validation and call another function doSubmit(); If I have 3 different forms, all forms calls doSumbit();
How to make different submission call based on the related form... also how to handle related form field validation...
As I understood. You have to give each form an id.
And then you can use this.
if(e.target.id==='formid1'){
console.log('formid1');
}
else if(....
** you can use for="id of your form" in your button **
<form id="myForm" method="post">
<input type="text" id="username" name="username" required>
<center><button for="myForm" type="submit">Continue</button> </center>
</form>
I have added a pattern attribute to my custom input field in the Shopify add to cart form.
The problem is that the pattern validator won't pass unless i refresh the page after it has caught something in the validation.
I have tried to reset the form with .reset and it works, but the custom validation messages won't work in that case.
<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="{{ section.settings.text-custom-name-placeholder }}" name="properties[Ditt namn]">
var input = document.getElementById('add-your-name-here');
input.oninvalid = function(event) {
if ($(".wgcurrent").hasClass("en")) {
event.target.setCustomValidity("Letters only please");
} else if ($(".wgcurrent").hasClass("sv")) {
event.target.setCustomValidity("Vänligen ange endast bokstäver");
}
}
It works like this, except that the custom validation message won't display.
var input = document.getElementById('add-your-name-here');
input.oninvalid = function(event) {
if ($(".wgcurrent").hasClass("en")) {
document.getElementById("addtocart").reset();
event.target.setCustomValidity("Letters only please");
} else if ($(".wgcurrent").hasClass("sv")) {
document.getElementById("addtocart").reset();
event.target.setCustomValidity("Vänligen ange endast bokstäver");
}
}
I want the validation to work without having to refresh the page as it's not a very nice user experience.
You need to clear the Custom Validation message on input event. To do so use,
setCustomValidity('');
Check working code snippet below.
var input = document.getElementById('add-your-name-here');
input.oninput = function(event){
event.target.setCustomValidity('');
}
input.oninvalid = function(event) {
event.target.setCustomValidity("Letters only please");
}
<form action="#">
<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="Add text here" name="properties[Ditt namn]">
<button type="submit">Submit</button>
</form>
More details on Constraints Validation at MDN
i have create eway paynow button within form.
<form action="?" method="POST">
Name: <input type="text" name="customer_name" value="" />
<script src="https://secure.ewaypayments.com/scripts/eCrypt.js"
class="eway-paynow-button"
data-publicapikey="epk-6AEE4269-0010-4415-A327-8064928AEFD0"
data-amount="0"
data-currency="AUD"
data-allowedit="true"
data-resulturl="http://example.com/responseMsg.php">
</script>
</form>
i need to check whether customer_name field empty or not before load eway payment
form. if customer_name field empty don't load eway payment form.how do i do this??can i run javascript to validate this form?
The Pay Now button doesn't provide a hook to run a function before opening the payment form, nor does it use event listeners at the moment. The solution here is to:
Capture the original onclick handler
Add a new event listener which performs validation, then calls the original onclick if successful.
I've stuck to pure JS for this, jQuery would allow a cleaner implementation :-)
Also note I've removed the data-resulturl attribute and moved the URL to form tag, otherwise the window may just redirect without submitting.
<form action="http://example.com/responseMsg.php" method="POST">
Name: <input type="text" name="customer_name" value="" />
<script src="https://secure.ewaypayments.com/scripts/eCrypt.js"
class="eway-paynow-button"
data-publicapikey="epk-6AEE4269-0010-4415-A327-8064928AEFD0"
data-amount="10"
data-currency="AUD"
data-allowedit="true"
data-submitform="yes">
</script>
</form>
<script>
window.onload = function() {
// Find the eWAY Pay Now button - note getElementsByClassName is IE9+
var ewayButton = document.getElementsByClassName("eway-button")[0];
// save and remove old onclick
var oldeWAYclick = ewayButton.onclick;
ewayButton.onclick = null;
// Add new listener with validation
ewayButton.addEventListener("click", function(e){
// Stop form from submitting itself
e.preventDefault();
// Example validation
var name = document.forms[0]["customer_name"].value;
if (name == null || name == "") {
alert("Please complete all fields");
return;
}
// Display payment form
oldeWAYclick();
}, false);
};
</script>
I have used parsley.js many times and have literally copied the code from my last use of parsley.
However, every time I submit the form the page refreshes. preventDefault seems to work on my other pages and stops the page from refreshing but for some reason when I tried now it won't work. Can anyone figure out why not?
<script>
$(function(){
$("#register_signup").submit(function(e){
e.preventDefault();
var form = $(this);
if ($('#rform').parsley( 'isValid' )){
alert('valid');
}
});
});
</script>
<form id='rform' name='rform' data-parsley-validate>
<input id='reg_password' class='register_input' type='text' autocomplete="off" data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword" placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" onClick="javascript:$('#rform').parsley( 'validate' );" value='Sign Up' />
</form>
You are binding the submit event to a input element. If you check the jquery $.submit() documentation, it states that:
The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.
This is your main problem and this is why alert will never be displayed (in fact, that code is never executed).
I would also change a few things:
$('#rform').parsley( 'validate' ) should be $('#rform').parsley().validate(), assuming you are using Parsley 2.*
$('#rform').parsley( 'isValid' ) should be $('#rform').parsley().isValid().
Use $.on() instead of $.submit().
Remove onClickfrom the register_signup element. Since you are already using javascript, I would do this directly in the javascript code instead of onclick. This is more a personal preference.
So, your code will be something like this:
<form id='rform' name='rform'>
<input id='reg_password' class='register_input' type='text' autocomplete="off"
data-parsley-trigger="change" placeholder='Password' required>
<input id='reg_cpassword' class='register_input' type='text' name="reg_cpassword"
placeholder='Confirm password' data-parsley-equalto="#reg_password" required>
<input id='register_signup' type="submit" value='Sign Up' />
</form>
<script>
$(document).ready(function() {
$("#rform").on('submit', function(e){
e.preventDefault();
var form = $(this);
form.parsley().validate();
if (form.parsley().isValid()){
alert('valid');
}
});
});
</script>
if you are using parsely 2 you can try this
$(function () {
//parsely event to validate form -> form:valiate
$('#rform').parsley().on('form:validate', function (formInstance) {
//whenValid return promise if success enter then function if failed enter catch
var ok = formInstance.whenValid()
//on success validation
.then(function(){
alert('v');
formInstance.reset();
})
//on failure validation
.catch(function(){
formInstance.destroy();
});
$('.invalid-form-error-message')
.html(ok ? '' : 'You must correctly fill *at least one of these two blocks!')
.toggleClass('filled', !ok);
// console.log(formInstance);
if (!ok)
formInstance.validationResult = false;
console.log(formInstance);
});
//parsely event to submit form -> form:submit
$('#rform').parsley().on('form:submit', function (formInstance) {
// if you want to prevent submit in any condition after validation success -> return it false
return false;
});
//default submit still implemented but replaced with event form:submit
$('#rform').submit(function () {
alert('dd');
});
});
for more details parsely documentation check Form with examples and events
When you apply data-parsley-validate to your form, you don't need to apply javascript to form to stop submit until all validation run.
But if you applying javascript return false when parsely() not valid.
And just make sure you have include parsley.js code file.