I have 3 forms in the same page and I want to validate when I click the button, but I have to click twice.
$(document).ready(function () {
$(".form_foo").submit(function (e) {
salvaformRisposta($(this).attr('id'));
e.preventDefault(e);
});
});
function validateForm(form_id) {
$("#"+form_id).validate({
rules: {
},
submitHandler: function (form) {
salvaformRisposta(form);
}
});
}
UPDATE:
I resolved with
$(".form_foo").each(function(key, form) {
validateForm(form.id);
});
//
$(".form_foo").submit(function (e) {
console.dir($(this).attr('id'));
validateForm($(this).attr('id'));
e.preventDefault(e);
});
You can do something like that
$(document).ready(function(){
$('#your_form_id').validate({
rules: {
....
}, messages: {
...
}, submitHandler: function (form) {
//insert here your code if validation is ok
}
}
});
insert this snippet in a forEach
$(document).ready(function () {
validateForm('form_Id');
});
Try to Invoke validateForm() method in your document ready event.
substitute 'form_Id' with real form Id
Related
I'm trying to implement jQuery Validation Plugin v1.19.2 (http://jqueryvalidation.org/), it doesn't trigger automatically at first. It only activates afterI I hit enter or submit the form. Once I have hit enter or submit form then it works on keyup.
Please see following gif to understand what I mean. The first field (title) is required, as you can see that I enter text there, and then delete a few times but it does not show any error. But after I submit, then each time it shows error.
Here's the JSFiddle link: http://jsfiddle.net/ubwq95e8/
$(document).ready(function() {
$("form#signup").validate({
rules: {
title: {
required: true
},
},
});
});
Try to add onkeyup in $("form#signup").validate.
See document: https://jqueryvalidation.org/validate/#onkeyup
onkeyup: function(element) {
$(element).valid();
},
The plugin doesn't validate on onkeyup event by default, you need to implement it as per your requirements. Here's a simple example:
$("form#signup").validate({
onkeyup: function (element, event) {
$(element).valid();
},
rules: {
title: {
required: true
},
},
errorPlacement: function(error, element){}
});
Similarly for other event like onclick, onfocus* etc
just add a custom event for check inputs when focusout
$(document).ready(function() {
$("form#signup").validate({
rules: {
title: {
required: true
},
},
errorPlacement: function(error, element){}
});
$('#signup input').focusout(function(){
var form = $( "#signup" );
form.valid()
})
});
here is new jsfiddle with codes that work for your case
http://jsfiddle.net/qhsj84en/
I have put conditon to my form that one capital one small and 8 characters simply if criteria does not match my form should not be submit but here my form is submitted even this criteria does not match and showing me the success message.
I dont know where is the problem.
My js/ajax code:
$('#password_change_form').submit(function(e) {
e.preventDefault();
var saveThis = $(this);
$.ajax({
type: "POST",
url: "/changepassword",
data: $(saveThis).serialize(),
success: function(data) {
$(".success-messages").text("Heslo bylo úspěšně změněno").fadeIn();
setTimeout(function(){
$(".success-messages").fadeOut('slow');
},4000);
$('#password_change_form').trigger("reset");
},
error: function (data) {
$(".error-messages").text("Zadali jste špatné heslo").fadeIn();
setTimeout(function(){
$(".error-messages").fadeOut('slow');
},4000);
$('#password_change_form').trigger("reset");
}
});
}),
and validation rules on my form:
var FormValidation = function () {
var e = function () {
var e = $("#password_change_form"),r = $(".alert-danger", e), i = $(".alert-success", e);
e.validate({
errorElement: "span",
errorClass: "help-block help-block-error",
focusInvalid: !1,
ignore: ":hidden",
rules: {
new_password: { required: !0,password_validate:!0 },
password_confirmation: {
equalTo: "#new_password"
}
},
messages: {
new_password:{ required: "Zapomněli jste zadat nové heslo."},
password_confirmation:{ equalTo: "Hesla nesouhlasí."}
},
invalidHandler: function (e, t) {
i.hide(), r.show()
},
errorPlacement: function (e, r) {
r.is(":checkbox") ? e.insertAfter(r.closest(".md-checkbox-list,.checkbox-label, .md-checkbox-inline, .checkbox-list, .checkbox-inline"),r.closest(".checkbox").addClass("has-error")) : r.is(":radio") ? e.insertAfter(r.closest(".md-radio-list, .md-radio-inline, .radio-list,.radio-inline")) : e.insertAfter(r)
},
highlight: function (e) {
$('.help-block').html('');$(e).closest(".form-group").addClass("has-error")
},
unhighlight: function (e) {
$(e).closest(".form-group").removeClass("has-error")
},
success: function (e) {
e.closest(".form-group").removeClass("has-error")
}
})
};
return {
init: function () {
e();
}
}
}();
$(document).ready(function () {
FormValidation.init();
$.validator.addMethod("password_validate",function(value,element){
return this.optional(element) || /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);
},"Nové heslo musà obsahovat minimálnÄ› 8 znaků, jedno velké a malé pÃsmeno a ÄÃslo. ProsÃm zkontrolujte, že vámi zadané heslo splňuje tyto podmÃnky.");
});
I dont know where is the problem my form should not be submit if the criteria does not match but here its submitting the form.
Guys really needs your help here.
I suggest using Laravel validation for your form. https://laravel.com/docs/5.7/validation
This might also be useful: Laravel password validation rule
I have a script which validates the inputs entered upon an onmouseout event. Firstly when the user move the cursor away from the first input, the validation occurs and the error message is shown. I want to do the same process with the second input, that is, an error message is shown when the cursor is moved away from the second input. Below is my code:
<script type="text/javascript">
$('document').ready(function () {
$('#Make').on('mouseout', function () {
$("#carform").validate({
rules: {
Make: {
required: true
}
},
messages: {
Make: {
required: "Please enter a make"
}
},
submitHandler: function (form) {
form.submit();
}
});
if ($("#carform").valid()) {
//Do some code
}
});
$('#Model').on('mouseout', function () {
$("#carform").validate({
rules: {
Model: {
required: true
}
},
messages: {
Model: {
required: "Please enter a model"
}
},
submitHandler: function (form) {
form.submit();
}
});
if ($("#carform").valid()) {
//Do some code
}
});
});
</script>
My view:
<div>
<form id="carform" method="post">
<p>
#Html.LabelFor(l=>l.Make)
#Html.TextBoxFor(l => l.Make)
</p>
<p>
#Html.LabelFor(l=>l.Model)
#Html.TextBoxFor(l => l.Model)
</p>
<p>
<input id="createCar" type="submit" value="Submit"/>
</p>
</form>
</div>
When I move my cursor away from the input Make, the error message is seen. But when I do the same with the second input Model, no error message is seen. Any idea where I am doing it wrong?
You just need to initialize it once.. Not on each input blur and you have option in jquery validation which validates on blur which is as below:
onfocusout
Type: Boolean or Function()
Validate elements (except checkboxes/radio buttons) on blur. If
nothing is entered, all rules are skipped, except when the field was
already marked as invalid.
Set to a Function to decide for yourself when to run validation.
A boolean true is not a valid value.
Example: Disables onblur validation.
$(".selector").validate({
onfocusout: false //Do not use false instead use a callback function
});
The callback gets passed two arguments:
element
Type: Element The element currently being validated, as a DOMElement.
event
Type: Event The event object for this focusout event.
So you can make use of callback function as below in your case:
$('document').ready(function () {
$("#carform").validate({
onfocusout: function(element) {
this.element(element);
},
rules: {
Make: {
required: true
},
Model: {
required: true //keep both the required here
}
},
messages: {
Make: {
required: "Please enter a make"
},
Model: {
required: "Please enter a model" //keep both the messages here
}
},
submitHandler: function (form) {
if ($(form).valid()) { //check for valid form here
form.submit()//submit here
}
}
});
$('#Make,#Model').on('blur', function() {
$("#carform").validate().element( this );
});
});
Simple, define a same class for both inputs say class foo
and check mouseout event with class as an identifier like:
$('.foo').on('mouseout', function () {
// your code here
});
How would I add additional functionality to the jQuery validation submitHandler that is set in another script? I cannot modify the source JavaScript that is defining the submitHandler in the first place. Instead, I need to add some additional functionality to it from a subsequent script that runs. Here is some scaled-down pseudo-code for the .js file that is defining the submitHandler in the first place--which I cannot directly modify:
$("#frmReg").validate({
invalidHandler: function(e, validator) { //code here ... not relevant },
submitHandler: function() {
window.onbeforeunload = null;
$('#myForm')[0].submit();
},
rules: { firstname: { required: true } },
messages: { firstname: { required: 'First name is required' } }
});
Essentially, I want to bind a second function to the existing submitHander.
I glanced over the source and I think this should work:
var validatorInstance = $("#frmReg").validate(), //Call this AFTER the initial registration,
submitHandler = validatorInstance.settings.submitHandler;
validatorInstance.settings.submitHandler = function(){
//Do your custom stuff here
console.log(true);
return submitHandler.apply(this,arguments); //forward to the old handler
};
here's my call to the validate function. Everything works fine with this code.
$('#createForm').validate(function () {
});
But when I try to modify it a bit, the whole validation stop working:
$('#createForm').validate(function () {
errorPlacement: function(error, element) {
error.insertAfter(element);
},
debug:true
});
Any Idea?
you shouldn't have function() in there. change it to:
$('#createForm').validate(
{
errorPlacement: function(error, element) {
error.insertAfter(element);
},
debug:true
}
);
the stuff in the { } is the options. it's not a function :)
just remove function () in .validate(function () { and that should work...