Preventing form submission after validation by parsley.js - javascript

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.

Related

Placeholder only appears for split second [duplicate]

I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>

how to validate form when click eWAY paynow button

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>

Submit button is refreshing the page

I have a form inside of an mvc project and sending the inputs with post method to the controller. Everything is good if I use a "button", but it keeps refreshing the page if I change it to "submit".
html:
<form role="form" id="login">
<div class="form-group">
<input type="text" class="form-control border-purple" id="postCode" placeholder="Postcode" value="3208SC">
</div>
<div class="form-group">
<input type="text" class="form-control border-purple" id="huisNummer" placeholder="Huisnummer" value="20">
</div>
<div class="form-group">
<input type="email" class="form-control border-purple" id="eMail" placeholder="EMail" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-zoeken" id="btnZoeken">#ReinisResource.SidebarButton</button>
</div>
</form>
and this is my js code:
$("#login").submit(function() {
$("#mapStuff").empty();
$("#items").empty();
$("#historie").empty();
var selectedEmp = $(".drpDown :selected").text();
var postCodex = $("#postCode").val();
var huisNummerx = $("#huisNummer").val();
var eMailx = $("#eMail").val();
$("#empName").html(selectedEmp);
$.post("/Home/GetAddressCount", { postCode: postCodex, huisNumber: huisNummerx, eMail: eMailx }, function (response) {
if (response.Count === 0) {
$("#pers-info").hide();
$("#btn-section").hide();
$("#multipleAdd").hide();
document.getElementById('inCorrectInfo').click();
} else {
$("#employeesList").hide();
$("#pers-info").show();
var houseInfo1 = response.Straat + " " + huisNummerx;
var houseInfo2 = postCodex + " " + response.Woonplaats;
$("#perceelInfo").html(houseInfo1 + "<br>" + houseInfo2);
$("#meldingMaken-btn").addClass("active");
$("#historie-btn").removeClass("active");
if (response.Count === 1) {
$("#multipleAdd").hide();
reinis.ShowMapStuff();
reinis.ShowItemStuff();
} else {
reinis.ShowMultipleAddress();
}
}
});
});
If you ask me why I need to change it to "submit" from "button" I wanted to add Jquery validation. And I think submit is better to use it for good coding.
Thanks in advance
Since it is a submit event, it will submit unless you do preventDefault or return false, as i can see you need to '$.post` .
So it would be like this.
$("#login").submit(function(event){
event.preventDefault();
// followed by your code for $.ajax
});
More info- http://www.w3schools.com/jquery/event_preventdefault.asp
The event.preventDefault() method stops the default action of an element from happening.
For example: Prevent a submit button from submitting a form ( this is your case).
The default behavior of the <submit> and <button> element is to submit the form and redirect to another location. In order to prevent the page from being reloaded, make sure to prevent that behavior:
$("#login").submit(function(e) {
e.preventDefault();
// Your code here
});
A slightly less convenient method is to use return false, but you have to be careful because it is simply the shorthand of e.stopPropagation() and e.preventDefault(). It will prevent events from bubbling up, so if you are sniffing for events higher up in the DOM tree that originate from the #login element they will be lost.
Also, return false;, unlike e.preventDefault() has to be placed on the last line of the function so that it doesn't stop the function from being executed midway, i.e.:
$("#login").submit(function(e) {
// Your code here
// Last line
return false;
});
Well, that's what a submit button does :)
You can override this behavior by preventing the default behavior of the event when handling the submit event of the form:
$("#login").submit(function(e) {
e.preventDefault();
// the rest of the code
});
Ideally, in order to achieve graceful degradation, the submit button (and the form in general) should still perform the necessary actions for the application by way of posting the form and reloading the page. So the form should have an action which invokes the server-side operation being invoked.
Then the JavaScript code would override that behavior (using the above method) and provide a more UX-friendly AJAX approach to the operation being invoked.
Both should work, so that JavaScript isn't required in order to use the application.

How to create html5 custom validation?

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>

Preventing submission after jQuery Validation Engine

Once clicking button, wanting to prevent submission to local storage if any required fields are not filled out. Both functions work properly. Just trying to prevent LocalStorage.save() from hitting if $("#formID").validationEngine(); finds a required field not completed.
<form id="formID" name="myForm">
<input class="validate[required]" type="text" id="agree" name="agree"/>
<button type="submit" value="Save" id="Save" onclick="clicked();">Submit Survey</button>
</form>
<script type="text/javascript">
function clicked() {
if (confirm('Are you sure you want to submit?')) {
$("#formID").validationEngine();
my.LocalStorage.save();
} else {
return false;
}
}
</script>
From their documentation at http://posabsolute.github.io/jQuery-Validation-Engine/:
validate
Validates a form or field, displays error prompts accordingly.
Returns true if the form validates, false if it contains errors.
It is inversed for fields, it return false on validate and true on errors.
When using form validation with ajax, it returns undefined, the
result is delivered asynchronously via function options.onAjaxFormComplete.
// form validation
alert( $("#formID1").validationEngine('validate') );
// field validation
alert( $("#emailInput").validationEngine('validate') );
So that would change your code to:
function clicked (e)
{
if ( confirm('Are you sure you want to submit?') )
if ( $("#formID").validationEngine('validate') )
my.LocalStorage.save();
e.preventDefault();
}
Take note that I added e as a parameter that needs event passed in via:
<button type="submit" value="Save" id="Save" onclick="clicked(event);">
Submit Survey
</button>
From source code there is a function validate() which returns true/false after validating
so use it
if( $("#formID1").validationEngine('validate'))
{
my.LocalStorage.save();
}
check this http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

Categories

Resources