jQuery validation plugin. Validation for non form fields? - javascript

Ні, all!
I have a little question about jQuery.Validation plugin: - Can I complete validation for input fields that are not form fields (i.e no in the "form" tag) using jQuery.Validation plugin?
Thanks.

Yes you can, but the field still needs to be inside a set of <form> tags. However, you do not need to "submit" this form in order to check validation on the field(s) inside. You use the .valid() method to check this form independently of form submission.
http://jsfiddle.net/9fgVN/13/
<form id="myNonsubmitForm" action="#">
<textarea name="comments" id="comments" rows="5" cols="30"></textarea>
</form>
<button id="myButton">Click to Check Validation Status</button>
<input type="text" id="output" />
$(document).ready(function() {
$("#myNonsubmitForm").validate({
validClass: 'valid', // as per your configuration
rules: { // set rules as per your configuration
comments: {
required: false,
maxlength: 10
}
},
errorPlacement: function(error, element) {
// use this to control placement of error messages
// removal of errorPlacement handler will result in message appearing next to field automatically.
}
});
$("#myButton").click(function() { // validate on button click for this example
if($("#myNonsubmitForm").valid()){
$('#output').val('passed');
} else {
$('#output').val('failed');
};
});
});

Related

How to validate form based on input type=text/radio/checkbox using jQuery Validation Plugin

I have a multi step form with dynamically generated fields that I need to validate using jQuery, this is the form . How I can achieve this ?
// next step
$('.form-horizontal .btn-next').on('click', function() {
$("#multiphase").validate();
$('input[type="text"]').each(function(){
$(this).rule('add', {
required: true,
messages:{
required: "This field is required"
}
})
})
});
First of all, you can validate elements using "name" attribute. you can show below example:
<script type="text/javascript">
$("#pseudoForm").validate({
onfocusout:true,
rules:{
first_name:"required",
last_name:"required"
}
});
</script>
<!-- whatever -->
<div id="pseudoForm">
<input type="text" name="first_name"/>
<input type="text" name="last_name"/>
</div>
also you can see reference as this link LINK
You should map the input fields to an object containing the rules for the validation plugin. I assume you're using this: http://jqueryvalidation.org/
Here's the general idea:
var fields = {};
$('form').find(':input').each(function() {
fields[this.name] = "required";
});
$('form').validate({
rules: fields
});
Of course you have to configure the plugin a bit more, but this is how you will handle the dynamic fields at least. An alternative would be to generate the rules server-side.

Set jquery selector dynamically based on HTML form ID value

I have several forms on one page that differ based on the forms' IDs. The ID's differ by an appended _0, _1, _2 etc (an index value created by a rails each do loop).
I'm trying to validate these forms, however to keep my code DRY, I'd like the form selector to be dynamic. I need to somehow grab the form's ID value ("_0") and add it to the jQuery selector.
This Fiddle gives an exmaple of how I'm tackling the problem now.
The code inside of the validation() block is the same between the jQuery functions. I need to set the selector variable to something like this:
$("new_loan_question_answer_"+i)
I'm not sure how to pass the _0 or _1 form the HTML form to the jQuery function.
form html
<div class="form">
<p>Question #1 text</p>
<form id="question_response_0">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form id="question_response_1">
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
jquery
$(function () {
$("#question_response_0").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
$(function () {
$("#question_response_1").validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
Don't bother with incremental id attributes. It becomes a pain to maintain and leads to issues keeping code DRY. This kind of thing is exactly what classes were invented for:
<div class="form">
<p>Question #1 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
<div class="form">
<p>Question #2 text</p>
<form class="question_response"> <!-- < use a common class on the form -->
<input type="text" name="response"></input>
<input type="submit">
</form>
</div>
Now you only need to attach validate to the .question_response class. Unfortunately it seems that the error highlighting (and possibly other features) is bugged in the validate plugin when instantiating on a selector that contains multiple form elements, so you need to loop through each form in turn:
$(function () {
$('.question_response').each(function() {
$(this).validate({
rules: {
"response": {
required: true
}
},
messages: {
"response": {
required: 'This field is required'
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
});
Example fiddle
Check out http://api.jquery.com/submit/ for example.
If you use an event handler to call a function, then the event may contain the information you need (ID of submitted form).
Information regarding the event object is available here: http://api.jquery.com/category/events/event-object/
Could use the classes shown already in your markup, or add a class to form tags:
$('div.form form').validate({/* options*/}) ;
This will include all forms that match the selector and each will have it's own validation instance

Bootstrap JS validator and form submit

I am using this Bootstrap validator github.com/1000hz/bootstrap-validator for my bootstrap forms but it appears there is no way to set some external JS conditional before submitting forms.
For example, I would like to do the following from an external JS files:
1 # if form or some input of the form is invalid using validator() then I do some action.
2 # else Users will see some bootstrap button loading message until everything is submitted into the databases.
You can have a single case here:
$('button[data-loading-text]').click(function () {
var btn = $(this);
btn.button('loading');
$.blockUI();
// #1 if form is invalid using validator() then I unblock the please wait message $.unblockUI(); and reset the bootstrap loading button.
// #2 else users will still see the "please wait" message + bootsrap loading button untill everything is submitted into the databases.
});
http://jsfiddle.net/temgo/k07nx06k/12/
Any help will be appreciated as it appears the plugin events are only set for specific field not for full form validation.
Regards
Check out the Events section on 1000hz page. (http://1000hz.github.io/bootstrap-validator/#validator-events)
If you want to fire up the action before validating - just listen to the event.
$('#someFormId').on('validate.bs.validator', function(){
doSomeStuff();
});
Edit
The problem with events is that it is fired after every field. From what I know this plugin doesn't provide an event for finished successful validation.
For your ref hope it will help u
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('Done');
}
});
});
I came across this question looking for something else, but I have worked on precisely what you're trying to achieve.
My solution was to use the snippet of code the plugin author gives for binding to the submit button
$('#form').validator().on('submit', function (e) {
if ( !e.isDefaultPrevented() ) {
// put your conditional handling here. return true if you want to submit
// return false if you do not want the form to submit
}
});
Hope that helps someone out.
$(function () {
$("#myForm").validator();
$("#myButton").click(function (e) {
var validator = $("#myForm").data("bs.validator");
validator.validate();
if (!validator.hasErrors())
{
$("myForm").submit();
} else
{
...
}
}
})
Hope with will help.
I am working so much for a better coding with this form validator js plugin.
Follow my code and try yourself:
// Select every button with type submit under a form with data-toggle validator
$('form[data-toggle="validator"] button[type="submit"]').click(function(e) {
// Select the form that has this button
var form = $(this).closest('form');
// Verify if the form is validated
if (!form.data("bs.validator").validate().hasErrors()) {
e.preventDefault();
// Here go the trick! Fire a custom event to the form
form.trigger('submitted');
} else {
console.log('Form still not valid');
}
});
// And in your separated script, do the following:
$('#contactForm').on('submitted', function() {
// do anything here...
})
Consider the following HTML code:
<form id="contactForm" action="/contact/send" method="POST" data-toggle="validator" role="form">
<div class="form-group has-feedback">
<label for="inputName" class="control-label">Name:</label>
<input type="text" name="inputName" id="inputName" class="form-control" data-error="Your input has an invalid value"/>
<span class="help-block with-errors"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Send</button>
</div>
</form>
you can use validated.bs.validator to hand the event in order to do something after validating the form.
Regards!

Preventing form submission after validation by parsley.js

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.

jQuery validate display error message in div

I am new with jQuery validation and learing so I don't have any idea about this. Now I am using jQuery Validate plugin and want to display error message inside div element. I have created div for every error message.
For example I have Name input field and want to display error message inside nameError div.
<div>
<label for="name">Name</label>
<input id='name' name="name" value="" />
</div>
<div id="nameError">
<!-- Display Name Error Here -->
</div>
Is it possible for jQuery Validation Plugin? I have no idea that why I am posting here to get help from you.
MY JQUERY CODE IS:
$(function () {
$.validator.addMethod("regex", function (value, element, regexpr) {
return regexpr.test(value);
}, "Please enter a valid name.");
$("#myForm").validate({
rules: {
name: {
required: true,
regex: /^[A-Za-z]+$/
}
}
});
});
MY JSFIIDLE
Thanks.
Here's a quick sample: http://jsfiddle.net/4PuJL/7/
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
error.appendTo('#nameError');
}
});
You may add a check in errorPlacement handler like below:
Please note that errorPlacement function is called for each error, if you need more handling on error message, please check for invalidHandler
jQuery.validator.setDefaults({
errorPlacement: function(error, element) {
if (element.attr("name") == "name" ) //Id of input field
error.appendTo('#nameError');
if (element.attr("name") == "anotherInputField" ) //Id of input field
error.appendTo('#anotherInputFieldError');
}
});
check the following link
My Fiddle
HTML :
<form>
<input type="text" required pattern="/^[A-Za-z]+$/" >
<input type="submit" value="search">
</form>

Categories

Resources