I have a form and I used field validator on it and its working fine but when i open form in edit mode and empty field and press save bootstrap Validator not works.
Below is the validator code
$(document).ready(function () {
$('#frmSpecialtyDetail')
.bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
ShortName: {
group: '.col-md-6',
validators: {
notEmpty: {
message: 'Short Name is required'
}
}
}
}
});
});
Taken from the original BootstrapValidator website, this is the code you have to use in order for the form to submit once it succeeds with the validation:
$(document).ready(function() {
$(form)
.bootstrapValidator({
... options ...
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
// ... Process the result ...
}, 'json');
});
});
In your case I'd do something along the lines of:
$(document).ready(function() {
$('#frmSpecialtyDetail')
.bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
ShortName: {
group: '.col-md-6',
validators: {
notEmpty: {
message: 'Short Name is required'
}
}
}
}
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
// ... Process the result ...
}, 'json');
});
});
Hope that helps.
Source: http://bootstrapvalidator.com/examples/ajax-submit/
Related
This question already has answers here:
Jquery file validation
(5 answers)
Closed 2 years ago.
Hi i have a html form with an input file and many more fields .I am going to validate it by jquery form validator plugin . It works like a charm for text inputs and selects but it just validate file input when it is empty. When I choose a file in any wrong type or wrong size , even if I didn't filled other required text input , it submit the form in GET method.this is my jquery code:
$("#form").validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-error-label',
successClass: 'validation-valid-label',
highlight: function (element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function (element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function (error, element) {
// Styled checkboxes, radios, bootstrap switch
if (element.parents('div').hasClass("checker") || element.parents('div').hasClass("choice") || element.parent().hasClass('bootstrap-switch-container')) {
if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent().parent().parent());
} else {
error.appendTo(element.parent().parent().parent().parent().parent());
}
}
// Unstyled checkboxes, radios
else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {
error.appendTo(element.parent().parent().parent());
}
// Input with icons and Select2
else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo(element.parent());
}
// Inline checkboxes, radios
else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
error.appendTo(element.parent().parent());
}
// Input group, styled file input
else if (element.parent().hasClass('uploader') || element.parents().hasClass('input-group')) {
error.appendTo(element.parent().parent());
}
// Inline checkboxes, radios
// else if (element.parents().hasClass('uploader')) {
// error.appendTo(element.parent().parent().parent().parent());
// }
else {
error.insertAfter(element);
}
},
validClass: "validation-valid-label",
success: function (label) {
label.addClass("validation-valid-label").text("معتبر.")
},
rules: {
title: {
required: true,
minlength: 8
},
unique_name: {
required: true,
minlength: 3
},
lang: {
required: true,
},
style: {
required: true,
},
image01: {
required: true,
// extension: "gif|png|jpg|jpeg", // work with additional-mothods.js
accept: "image/jpeg, image/pjpeg",
filesize: 1000000, // 1MB, this filesize method is the custom method that I create. the code can be found in this post.
}
},
messages: {
image01: {
require: "لطفا لوگوی سایت را انتخاب نمایید",
filesize: "حجم مجاز فایل ۱ مگابایت می باشد",
extension: "فرمت مجاز فایل jpeg,gif,png می باشد"
},
title: {
required: "لطفا فیلد را با حداقل 8 کاراکتر کامل نمایید",
},
unique_name: {
required: "لطفا فیلد مورد نظر را کامل کنید",
minlength: "حداقل ۳ کاراکتر.کاراکترها بهتر است انگلیسی باشد"
},
lang: {
required: "لطفا زبان مورد نظر را انتخاب نمایید",
},
style: {
required: "لطفا قالب مورد نظر را انتخاب نمایید",
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
//enctype: 'multipart/form-data',
url: "/admin/{{ CURRENTCLASS }}/fullInsert",
data: new FormData($("#form")[0]),
datatype: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
//$("#loaderDiv").show();
},
success: function (result) {
result = $.parseJSON(result);
if (result.dataUpload === true && result.imageUpload === true) {
$('#modalheader').removeClass().addClass('modal-header bg-success');
$('.modal-title').html("ثبت اطلاعات");
$('#modal-msg').html(result.dataEntryMsg);
$('form')[0].reset();
} else if (!result.dataUpload) {
$('#modalheader').removeClass().addClass('modal-header bg-danger');
$('.modal-title').html("خطا در ثبت اطلاعات");
$('#modal-msg').html(result.dataEntryMsg);
$('form')[0].reset();
} else if (result.dataUpload == true & result.imageUpload == false) {
$('#modalheader').removeClass().addClass('modal-header bg-warning');
$('.modal-title').html("خطا در ثبت تصویر");
$('.modal-body').html(result.dataEntryMsg + "<br>" + result.imgUploadMsg);
}
$('#modal_theme').modal('toggle');
},
complete: function () {
//$("#loaderDiv").hide();
},
error: function (result) {
// alert('4');
// $('#modal_theme').modal('toggle');
// $("#loaderDiv").hide();
// $('.modal-body').html(result.msg);
// $('#delModal').modal('toggle');
}
});
return false; // required to block normal submit since you used ajax
}
});
after deep searching i found what is the problem. To validate extensions with jquery validation plugin you must include additional_methods.js file.it must be added after validate.js file. Hope it help you.
I have an array of dynamically added objects and I want to validate this array for required fields and numeric values.
I have 3 buttons, one for adding note, another for removing note and one for saving
How to validate every object ?
.. the code:
$(function () {
var initialData = [{
Title: "",
NoteText: "",
Suggestion: "",
MediaTime: ""
}];
var CreateNewNoteModel = function (Notes) {
var self = this;
self.Notes = ko.observableArray(ko.utils.arrayMap(Notes, function (Note) {
return { Title: Note.Title, NoteText: Note.NoteText, Suggestion: Note.Suggestion, MediaTime: Note.MediaTime };};
}));
var i = 1;
self.addNote = function () {
self.Notes.push({
Title: "", NoteText: "", Suggestion: "", MediaTime: ""
});
$('#editor' + i).wysihtml5();
$('#editorB' + i).wysihtml5();
i++;
};
self.removeNote = function (Note) {
self.Notes.remove(Note);
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.Notes), null, 2));
var jsondata = self.lastSavedJson();
$.ajax({
url: "/api/Notes/?mid=" + m + "&p=" + p,
cache: false,
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: jsondata,
success: function () {
alert("Success");
document.location.reload(true);
}
});
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new CreateNewNoteModel(initialData));
});
I am using jQuery validate plugin to add validation to knockout-js by using jQuery's validation methods: "$.validator.addMethod" and "$.validator.addClassRules".
Example:
First define your validation methods and css classes. Later on, we add the css classes to your inputs to validate your fields.
function DefineValidationRules() {
$.validator.addMethod("validateNumber", ValidateInteger, "This field is not a number");
$.validator.addMethod("validateRequired", $.validator.methods.required, "This field is required");
$.validator.addMethod("validateMin", $.validator.methods.min, $.format("This number be greater than or equal to {0}"));
$.validator.addMethod("validateMax", $.validator.methods.min, $.format("This number must be less than or equal to {0}"));
$.validator.addMethod("validateMinlength", $.validator.methods.minlength, $.format("This field must contain at least {0} characters"));
$.validator.addMethod("validateRangelength", $.validator.methods.rangelength, $.format("This field must contain between {0} and {1} characters"));
$.validator.addClassRules("validate-number", { validateNumber: true });
$.validator.addClassRules("validate-number-min", { validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required-number-min", { validateRequired: true, validateNumber: true, validateMin: 1 });
$.validator.addClassRules("validate-required", { validateRequired: true });
$.validator.addClassRules("validate-rangelengthmax6", { validateRangelength: [0,6] });
}
DefineValidationRules();
You can also add your own custom validation method:
function ValidateInteger(value) {
//do whatever you want to check
}
Having an input in knockout:
<input class="validate-required validate-number" type="text" data-bind="value: examplefield, valueUpdate: 'afterkeydown', attr: { attrname: 'itsvalue'}" />
Checking on submit:
$("#yoursubmitbutton").on("click", function () {
var formtosubmit = $("#idofyourform");
//check for validation errors
if (isValid(formtosubmit)) {
formtosubmit.submit();
//
// code to proceed to next step
}
});
function isValid(el) {
var $thisform = el;
$thisform.validate({
errorElement: "label",
errorPlacement: function (error, element) {
//eventual different error placing
if (element.attr("name") == "fname" || element.attr("name") == "lname") {
element.css("border", "2px solid red");
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
return $thisform.valid();
}
How can I prevent collection.create from adding items into its collection if there is an error found in the input?
html,
<div id="new-status">
<h2>New monolog</h2>
<form action="">
<textarea name="content"></textarea><br>
<input type="submit" value="Post">
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
backbone,
var Status = Backbone.Model.extend({
initialize: function(){
},
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
url:"dummy.php",
sync: function (method, model, options) {
return $.ajax({
type: "POST",
dataType: 'json',
url: 'server.php',
data: {
text: this.get("text")
}
});
}
});
var Statuses = Backbone.Collection.extend({
model: Status
});
var NewStatusView = Backbone.View.extend({
events: {
"submit form": "addStatus"
},
initialize: function(options) {
_.bindAll(this, 'addStatus', 'clearInput');
this.listenTo(this.collection, 'add', this.clearInput) ;
},
addStatus: function(e) {
e.preventDefault();
this.collection.create({ text: this.$('textarea').val() });
},
clearInput: function() {
this.$('textarea').val('');
}
});
var StatusesView = Backbone.View.extend({
initialize: function(options) {
this.collection.on("add", this.appendStatus, this);
},
appendStatus: function(status) {
this.$('ul').append('<li>' + status.escape("text") + '</li>');
}
});
$(document).ready(function() {
var statuses = new Statuses();
new NewStatusView({ el: $('#new-status'), collection: statuses });
new StatusesView({ el: $('#statuses'), collection: statuses });
});
So, when you hit the submit button without typing any text, you get an error popup from this part in the model,
validate: function(attrs, options) {
if(attrs.text === '') alert("please enter some text");
},
But how can I tell the collection that there is an error and do not add this empty item and also do not fire sync in the model?
EDIT:
got it worked with collection.create in this way...
model,
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
view,
addStatus: function(e) {
e.preventDefault();
var one = new Status({ text: this.$('textarea').val() });
if (!one.isValid()) {
alert(one.validationError);
} else {
this.collection.create(one);
}
},
it seems to work fine unless it is not a good approach or against MVC pattern?
I don't think collection.create is the right choice here.
addStatus: function(e) {
e.preventDefault();
var status = new Status({"text": this.$('textarea').val()})
var error = status.valiate();
if(!error) {
this.collection.add(status);
}
},
Also not that the backbone docs says this about validate:
If the attributes are valid, don't return anything from validate; if
they are invalid, return an error of your choosing. It can be as
simple as a string error message to be displayed, or a complete error
object that describes the error programmatically.
So, your validate function should be fixed:
validate: function(attrs, options) {
if(attrs.text === '') {
var message = "please enter some text";
alert(message);
return message;
}
},
Your Model's validate method should return an error string so that models save is not fired in case of alert.
validate: function(attrs, options) {
if(attrs.text === ''){
alert("please enter some text");
return "Text is empty."; // OR proper error CODE
}
}
Check validate method of Backbone.Model.
I am rather new to backbone and wanted to test a simple script that handles a to do list. Here is the code i used so far:
(function() {
window.App = {
Models: {},
Collections: {},
Views: {}
};
window.template = function(id) {
return _.template($('#' + id).html());
}
App.Models.Task = Backbone.Model.extend({
validate: function(attributes) {
if ( !$.trim(attributes.title) ) {
return 'Invalid title';
}
}
});
App.Collections.Tasks = Backbone.Collection.extend({
model: App.Models.Task
});
App.Views.Task = Backbone.View.extend({
tagName: 'li',
template: template('taskTemplate'),
initialize: function () {
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
events: {
'click .edit': 'editTask',
'click .delete': 'destroy'
},
destroy: function() {
if (confirm('Are you sure?')) {
this.model.destroy();
}
},
remove: function() {
this.$el.remove();
},
editTask: function() {
var newTaskTitle = prompt('New title:', this.model.get('title'));
this.model.set('title', newTaskTitle, {validate: true});
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
App.Views.AddTask = Backbone.View.extend({
el: 'form#addTask',
initialize: function() {
},
events: {
'submit': 'submit'
},
submit: function(event) {
event.preventDefault();
var newTaskTitle = $(event.currentTarget).find('input[type=text]').val();
var task = new App.Models.Task({ title: newTaskTitle });
this.collection.add(task, {add: true, merge: false, remove: false});
}
});
App.Views.Tasks = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.collection.on('add', this.addOne, this);
},
render: function() {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(task) {
var taskView = new App.Views.Task({ model: task });
this.$el.append(taskView.render().el);
}
});
var tasks = new App.Collections.Tasks([
{
title: 'Go to store',
priority: 4
},
{
title: 'Go to mall',
priority: 3
},
{
title: 'Get to work',
priority: 5
}
]);
var addTaskView = new App.Views.AddTask({ collection: tasks });
var tasksView = new App.Views.Tasks({ collection: tasks });
$('div.tasks').append(tasksView.render().el);
})();
So the model validation works fine ... the only pb is that collection.add does not validate the newly added model .... is the a way to force the validation?
Thanks,
Rares
From the fine manual:
validate model.validate(attributes, options)
[...] By default validate is called before save, but can also be
called before set if {validate:true} is passed.
Collection#add does not call save nor does it call set with the validate: true option. If you want to validate during add, say so:
collection.add(models, { validate: true });
That will get validate:true all that way down to Model#set.
A quick look at a simplified example may be helpful:
var M = Backbone.Model.extend({
set: function() {
console.log('setting...');
Backbone.Model.prototype.set.apply(this, arguments);
},
validate: function() {
console.log('validating...');
return 'Never!';
}
});
var C = Backbone.Collection.extend({
model: M
});
var c = new C;
c.on('add', function() {
console.log('Added: ', arguments);
});
c.on('invalid', function() {
console.log('Error: ', arguments);
});
Now if we do this (http://jsfiddle.net/ambiguous/7NqPg/):
c.add(
{ where: 'is', pancakes: 'house?' },
{ validate: true }
);
You'll see that set is called with validate: true, validate will be called, and you'll get an error. But if you say this (http://jsfiddle.net/ambiguous/7b2mn/):
c.add(
{ where: 'is', pancakes: 'house?' },
{add: true, merge: false, remove: false} // Your options
);
You'll see that set is called without validate: true, validate will not be called, and the model will be added to the collection.
The above behavior is quite strongly implied but not explicitly specified so you may not want to trust it. Model#initialize does say:
you can pass in the initial values of the attributes, which will be set on the model.
and set does explicitly mention the validate option. However, there is no guarantee that Collection#add will send options to the model constructor or set or that the model's constructor will send the options to set. So if you want to be really paranoid and future proof, you could add a quick check for this "options get all the way down to set" behavior to your test suite; then, if it changes you'll know about it and you can fix it.
if you pass options to your collection add method, the validation method will not be called and as your arguments in this case are all set to the default value, there is not need to pass them
this.collection.add(task);
you may want to take a look at this question.
Prevent Backbone.js model from validating when first added to collection
Onsubmit I want to fire fancybox popup
I need only to show the fancybox popup once form is VALIDATED (JQUERY Validate used)
It seems to popup the fancybox popup only when the form is not filled in correctly!
http://gloss-hair.com/old/owl/OWLFORM.html
I am not sure how to load the popup fancybox function only once the form is validated:
<script type="text/javascript">
$().ready(function() {
// validate the competition form when it is submitted
$("#ie9_competition").validate({
errorPlacement: function (error, element) {
if ( element.is(":checkbox") ) {
error.appendTo( element.closest('div') );
}
else {
error.insertAfter(element.parent().find("label"));
}
},
rules: {
sEmail: {
required: true,
email: true
},
}
});
});
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox4").fancybox({
'hideOnContentClick': true
});
});
</script>
jQuery Validation plugin lets you define submitHandler which executes if a form is valid:
submitHandler: function(form){
form.submit(); // submit the form
// code to show your fancybox here
}
Your validate() code will look like this:
$("#ie9_competition").validate({
errorPlacement: function (error, element) {
if ( element.is(":checkbox") ) {
error.appendTo( element.closest('div') );
} else {
error.insertAfter(element.parent().find("label"));
}
},
rules: {
sEmail: {
required: true,
email: true
}
},
submitHandler: function(form){
form.submit(); // submit the form
// code to show your fancybox here
}
});
You can see all available options for validate() method here: http://docs.jquery.com/Plugins/Validation/validate#toptions
Try like this
$().ready(function() {
// validate the competition form when it is submitted
$("#ie9_competition").validate({
errorPlacement: function (error, element) {
if ( element.is(":checkbox") ) {
error.appendTo( element.closest('div') );
}
else {
error.insertAfter(element.parent().find("label"));
}
},
rules: {
sEmail: {
required: true,
email: true
},
},
submitHandler: function(form){
jQuery('.fancybox4').trigger('click');
}
});
});
Then remove the onsubmit event from form tag. So your form tag is like
<form id="ie9_competition" method="post">