Problem
JQuery Validate does not work. In the below plunker, Please click on "Please click here" button and then click on save. It will not validate form.
Sample code in Plunker
I have jQuery validation code which is working fine in case I open the add/update form in new page. I meant by redirecting the user to a new route.
$("form#" + createRoleForm).validate({
rules: {
},
messages: {
},
submitHandler: function(form) {
}
});
In case I open the add/update form on clicking the button in same page when I am inside List page...The above jQuery validate code does not work. I am assuming that I will need something like this...
$(document).ready(function() {
$(document).on("eventtype", "object", function() {
});
});
But, I am not sure how can I bind the validate event in this way....
Since your form is async, your element is not already on the dom when you are creating the validator.
What you should do is add the validate code on your ajax success function:
//...
success: function(result) {
$('#SaveRoleModal').html(result);
createValidator("form#" + createRoleForm)
return false;
},
//...
function createValidator(target) {
$(target).validate({
rules: {
Role: {
required: true
}
},
messages: {
Role: {
required: "Please enter Role"
}
},
submitHandler: function(form) {
console.log('ok :)')
}
});
}
Related
I am using bassistance.de's Validation jQuery plugin to validate a form #signup-form. Instead of submitting the form data directly to the server the usual way, the form data should be submitted AJAX'ly via $.post().
JS Code
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
});
Problem: If a user entered data that does not pass the jquery validation, the click handler on #submit-btn will still allow the form to be submitted! Is there a way to check that there are no validation errors?
Try this:
// Validate form
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
}
});
// Submit to Serverside
$('#submit-btn').click(function() {
if ($('.signup-form').valid()) {
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
The best way to do this is to use the submitHandler option to validate:
$('.signup-form').validate({
rules: {
signupName: { required: true, minlength: 3 }
},
submitHandler: function(form){
$.post('/api/register_user',
$('#signup-modal .signup-form').serialize(),
success: function() {
console.log('posted!');
}
);
}
});
This will automatically be called once the form is valid. No need to attach anything new to your submit button or the submit event.
I am having some problems on executing the following code.
The code submits but it doesnt do anything, it comes back to the same screen, it seems that the values of the form have been not submited.
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
debug: false,
rules: {
///
},
messages: {
///
},
submitHandler: function(form) {
var result;
$.post('test.php', $('#signin_form').serialize(), function(data){
result = $.parseJSON(data);
if (result.flag == 'false'){
$('#results').show()
}
})
.success(function(data){
if (result.flag == 'true'){
form.submit();
}
}, 'json');
}
});
});
</script>
If I change the code to the following, it works and it takes me to the proper screen, but i need to validate, a captcha code, i am not sure if it is the right place to do it, i tried to use beforeSubmit but then the captcha is not validated.
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
debug: false,
rules: {
///
},
messages: {
///
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
There is something about the $.post that i dont underestand... and doesnt submit the information.
Does anyone know what it could be?
thanks!
You don't need to change how the form submits, in this case, for validating the captcha, use remote function from jquery.validate.
There are some problems around the remote usage with jquery.validate. Check if you did the following:
1) Make sure you are using jQuery version 1.6.1 and above only.
2) Use the "synchronous" option for remote execution (default being asynchronous) and to do this set async argument to false.
Example of usage:
Suppose this is my form...
HTML:
Add id and name attributes to all the form elements or just the captcha (this one must have both).
<form id="signin_form" action="save.php" method="POST">
Enter captcha: O1S2C3A4R
<br/>
<input type="text" id="captcha" name="captcha" value=""/>
<input type="submit" id="save" name="save" value="Save"/>
</form>
jQuery:
Add type, async and data arguments. This last argument passes the captcha value to check.php file and that's why that element needs the id attribute. Then you are able to use this selector $('#captcha').
(For me this is better but you can also call the element by name using other selector type)
Just to know, you need to also define an error message for the remote, in this case I used Invalid captcha.
$(document).ready(function(){
$("#signin_form").validate({
rules: {
captcha: {
required: true,
remote: {
url:"check.php",
type:"post",
async:false,
data: {
/* this is the name of the post parameter that PHP will use: $_POST['captcha'] */
captcha: function() {
return $.trim($("#captcha").val());
}
}
}
}
},
messages: {
captcha: {
required: "*",
remote: "Invalid captcha"
}
}
});
});
PHP: check.php
At this point it is important to use "true" or "false" as string to let know the jquery.validation plugin if the captcha is valid or not. In this case, if captcha is equals to O1S2C3A4R then is valid and, at client side, you will look that the submit will process the form to save.php file specified in the html form action attribute.
<?php
$captcha = $_POST['captcha'];
if($captcha == "O1S2C3A4R"){
echo "true";
} else {
echo "false";
}
?>
Doing this way, you can validate the whole form without problems and also check the captcha value remotely without altering plugin functionality.
Also you can test all this code together and look that it works :-)
Hope this helps.
Javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#signin_form").validate({
rules: {
captcha: {
remote: {
url: "remote.php"
}
}
}
},
messages: {
captcha: {
remote: "Please enter the text in the captcha."
}
}
});
});
</script>
HTML form:
<form id="signin_form">
<input type="text" name="captcha">
<input type="submit">
</form>
PHP:
$response = $_GET['captcha'];
$answer = 'captcha_answer';
if($response==$answer){
echo 'true';
} else {
echo 'false';
}
Sorry for shoving this part into an answer -- I'm not allowed to comment:
Keep in mind that setting the 'async' parameter to false will lock up your page until you get a response, which might not be what you want. The validation library should block normal form submission if it's waiting on a response for remote validation, at least in newer versions (I'm using jQuery 1.7.2 and Validation 1.10.0).
IIRC the jQuery Validate library will treat anything other than the exact string "true" as being an error. This can be used to pass different custom messages depending on the reason for rejection. json_encode adds extra quotation marks that cause jQuery Validate to see it as a custom error message.
I'm submitting a form using the AJAX JQuery validation plugin. The code looks something like this:
$(document).ready(function(){
$("#myform").validate({
debug: false,
rules: {
fname: {required: true},
sname: {required: true},
gender: {required: true},
},
messages: {
fname: {required: " *"},
sname: {required: " *"},
gender: {required: " *"},
},
submitHandler: function(form) {
$('input[type=submit]').attr('disabled', 'disabled');
$('#results').html('Loading...');
$.post('process_participant.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
Now so the problem is after I send this information to my PHP page to be prcoessed (process_participant.php) I want to respond with a confirmation box asking if the user wants to add another participant. The PHP code looks something like this:
if (everything processes okay){
echo '<script type="text/javascript">';
echo 'input_box=confirm("Saved successfully. Would you like to add another participant?");
if (input_box==true) {
window.location = "new_participant.php"
}
else {
window.location = "home.php"
}';
echo '</script>';
}
This all works fine but the default confirmation box isn't acceptable. I need to be able to style it and change it from OK and CANCEL to YES and NO. I decided to use this plugin: http://kailashnadh.name/code/jqdialog/ and use the following code on the PHP side:
echo '<script type="text/javascript">';
echo " function confirmBox() {
$.jqDialog.confirm(\"Are you sure want to click either of these buttons?\",
function() { window.location = \"new_participant.php\"; },
function() { window.location = \"home.php\"; }
);
});";
echo "confirmBox();";
However I can't seem to get it to work. Maybe I should avoid using a plugin? The whole AJAX thing is making things confusing. Anyone know the best way to implement a custom confirm box in this situation?
create the box from the start with display:none
and when the function from the post request returns
do the checks (based on the variable data)
and if everything is ok change the visibility using jquery's show()
try this
its easy to implement just define your own html for alert and conform-box
I am using the jquery validate plugin to validate and submit a form on my page which has multiple submit buttons to run different functions.
One submit button runs using the $post method while the other uses the standard action method.
(Please stick with me if my terminology is wrong)
The problem I am having is that if I submit the form using the first button, then try again using the second button, it trys to run the first action again on the second submit.
Here's my code which will hopefully make things clearer...
<form id="myForm" action="add.php">
<input type="submit" id="myfunction" />
<input type="submit" id="add" />
<input type="text" name="myvalue" />
</form>
and my validate code...
$("#myForm input[type=submit]").click(function(e) {
if (e.target.id == 'myfunction') {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
} else if (e.target.id == 'add') {
$("#myForm").validate({
rules: {
name: {
required: true,
}
}
});
}
});
Why don't you seaprate the code into two segments?
$("#myfunction").click(function(e) {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
}
$("#add").click(function(e) {
$("#myForm").validate({
rules: {
name: {
required: true
}
}
});
}
You need to stop the form submission in the $.post case. Try returning false from the click event handler, that should stop the event from bubbling to the form and causing it to submit.
Personally I hook into the submit event on the form element instead of click events on the buttons. The reason is that many users submit forms by placing the cursor in a text box and then pressing enter. No click event ever occurs and your code is bypassed...
also, its been a while since i used the validate plugin, but i think you're using it wrong calling validate() after a form has been submitted. check the docs for proper use.
Just in case someone is looking for that.
Simple after the first submit use $("#myForm").validate().destroy(); in order to clear "form data".
https://jqueryvalidation.org/Validator.destroy/
I'm using the jQuery validation plugin and the form uses ajax to submit the form. I have a floating button bar which generates the buttons for pages depending on what the page is used for. These buttons sit outside of the form tag. My form's id is account-settings. In my document.ready I have this:
$("#account-settings").validate({
rules: {
email: {email: true}
},
messages: {
email: {email: "Enter a valid email address."}
},
})
There's a button called savesettings which saves the settings for the form. Here's the click event:
$('#savesettings').click(function() {
if($('#account-settings').valid()){
alert("Valid form");
}
else{
alert("Not valid");
}
}
Nothing happens when I click the button... so, basically, I'm obviously not using the plugin right, somebody enlighten me? Keep reading over the documentation but I don't see anything else...
You will need to serialize the form upon the user clicking the button something like..
$('#savesettings').click(function() {
var $as = $('#account-settings');
if($as.valid()){
$.post(
/* your server page */
, $as.serialize()
, /* your callback function */
);
}
else{
alert("Not valid");
}
});
I should point out the obvious accessibility pitfall with submitting a form this way where users with no JavaScript will not be able to use it.
If you want to submit a form using any button outside of that form, you should use the trigger() function like so:
$('body').on('click', '#my-button', function(){
$('#account-settings').trigger('submit');
});
Your validation plugin should then act as normal.
Your JS function could use a closing paren. Try something like:
$('#savesettings').click(function() {
if($('#account-settings').valid()){
alert("Valid form");
} else {
alert("Not valid");
}
});