I will use bootstrapvalidator, as I am using bootstrap. It works fine, but I have some contents I will load via ajax. When these contents contains forms, bootstrapvalidator will not work. I create a little example to demonstrate.
It bases on the formWithoutLabels.html example of the bootstrapvalidator download.
I copy formWithoutLabels2.html to formWithoutLabels2.html and replace the content of the form with
<div id="result">
</div>
In the javascript cart I add an ajax request
$( "#result" ).load( "content.html" );
formWithoutLabels2.html:
<!DOCTYPE html>
<html>
<head>
<title>BootstrapValidator demo</title>
<link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.css"/>
<link rel="stylesheet" href="../dist/css/bootstrapValidator.css"/>
<script type="text/javascript" src="../vendor/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="../vendor/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../dist/js/bootstrapValidator.js"></script>
</head>
<body>
<div id="result">
</div>
<script type="text/javascript">
$( "#result" ).load( "content.html" );
$(document).ready(function() {
$('#defaultForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
username: {
message: 'The username is not valid',
validators: {
notEmpty: {
message: 'The username is required and can\'t be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'The username must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z0-9_\.]+$/,
message: 'The username can only consist of alphabetical, number, dot and underscore'
}
}
},
email: {
validators: {
notEmpty: {
message: 'The email address is required and can\'t be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required and can\'t be empty'
},
identical: {
field: 'confirmPassword',
message: 'The password and its confirm are not the same'
}
}
},
confirmPassword: {
validators: {
notEmpty: {
message: 'The confirm password is required and can\'t be empty'
},
identical: {
field: 'password',
message: 'The password and its confirm are not the same'
}
}
}
}
});
});
</script>
</body>
</html>
</pre>
content.html:
<div class="container" style="margin-top: 50px;">
<div class="row">
<div class="col-lg-4 col-lg-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Sign up</h3>
</div>
<div class="panel-body">
<form id="defaultForm" method="post">
<div class="form-group">
<input type="text" class="form-control" name="username" placeholder="Username" />
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email" />
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="Password" />
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirmPassword" placeholder="Retype password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Sign up</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
In this example bootstrapvalidator does not work. What do I need to do, that it works within the ajax request?
Any ideas?
When you load content using an AJAX query there is a window of time that you need to wait before that content appears in the DOM. You can capture the event when that content is fully loaded by assigning a callback function:
$("#result").load("content.html", function() {
// attach validation to the form here
$("#defaultForm").bootstrapValidator({
// ...
});
});
This way, the bootstrapValidator function will be assigned after the content is loaded, not before.
See the documentation for load here: http://api.jquery.com/load/
Related
I am getting 3 different errors while submitting the data from the form
first error is : [Vue warn]: Error in mounted hook: "TypeError: this.getAllUsers is not a function"
and then if I test form validation without typing anything validation works but i get this error: [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'preventDefault' of undefined"
and then i fill in all the fields and click the submit button then i get this error: [Vue warn]: Error in v-on handler: "ReferenceError: axios is not defined"
Note: my API works perfectly
here's my code
this is the form
<template>
<b-container>
<div class="update-info">
<div class="feature-text myinv-title">
<h5 class="title title-sm">Update your information</h5>
</div>
<form id="app" #submit="saveUser" method="post" novalidate="true">
<p v-if="errors.length">
<b>Please fill in all the fields</b>
<ul>
<li v-for="error in errors" class="alert alert-danger">{{ error }}</li>
</ul>
</p>
<div class="form-row">
<div class="form-group col-md-3">
<label for="trx">TRX Address No.</label>
<input
id="trx"
class="form-control trx-address-nooverflow"
v-model="myAddress"
type="text"
name="TRX Address"
readonly
>
</div>
<div class="form-group col-md-3">
<label for="name">Name</label>
<input
id="name"
class="form-control"
v-model="name"
type="text"
name="name"
>
</div>
<div class="form-group col-md-3">
<label for="name">Country</label>
<country-select
id="Country"
class="form-control"
v-model="country"
:country="country"
topCountry="US" />
</div>
<div class="form-group col-md-3">
<label for="email">Email ID</label>
<input
id="email"
class="form-control"
v-model="email"
type="email"
name="email"
>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="email">Mobile No</label>
<input
id="mobile"
class="form-control"
v-model="mobile_no"
type="text"
name="mobile"
>
</div>
<div class="form-group col-md-3">
<div class="top-30">
<input type="submit" class="btn btn-btn btn-grad btn-submit" />
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</b-container>
</template>
this is the script
<script>
export default{
data(){
return{
errorMessage: "",
successMessage: "",
errors: [],
trx_no: "",
name: "",
country: "",
email: "",
mobile_no: "",
myAddress: "",
newUser: {trx_no: "", name: "", country: "", email: "", mobile: ""}
}
},
mounted: function(){
this.getAllUsers();
},
methods: {
saveUser(event){
event.preventDefault()
this.checkForm()
if(!this.errors.length) {
var formData = this.toFormData(this.newUser);
axios.post('http://localhost:8888/vue-and-php/public/api/update-info-form.php?action=update', formData, { crossdomain: true })
.then((response) => {
this.newUser = {trx_no: "", name: "", country: "", email: "", mobile: ""};
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.getAllUsers();
}
});
}
},
toFormData: function(obj){
var form_data = new FormData();
for(var key in obj){
form_data.append(key, obj[key]);
}
return form_data;
},
clearMessage: function(){
this.errorMessage = "";
this.successMessage = "";
},
//validation
checkForm: function (e) {
this.errors = [];
if (!this.name) {
this.errors.push("Name Required.");
}
if (!this.country) {
this.errors.push("Country Required.");
}
if (!this.email) {
this.errors.push('Email Required.');
} else if (!this.validEmail(this.email)) {
this.errors.push('Valid Email Address Required.');
}
if (!this.mobile_no) {
this.errors.push("Phone Number Required.");
}
if (!this.errors.length) {
return true;
}
e.preventDefault();
},
validEmail: function (email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
}
</script>
I am also posting my PHP code just for reference
<?php
//Import Database
require 'base.php';
if(isset($_GET['action'])){
$action = $_GET['action'];
}
//create
if($action == 'update'){
$trx_number = $_POST['trx'];
$name = $_POST['name'];
$country = $_POST['country'];
$email = $_POST['email'];
$mobile = $_POST['mobile_no'];
$result = $con->query(" INSERT INTO `update_information` (`id`, `trx_no`, `name`, `country`, `email`, `mobile_no`) VALUES (null,'$trx_number','$name','$country','$email','$mobile') ");
if($result){
$res['message'] = "Success";
}else {
$res['error'] = true;
$res['message'] = "Error";
}
$res['update_information'] = $update_information;
}
$con->close();
//encoding into json
echo json_encode($res);
die();
Here are the solutions to your errors
There is no method called getAllUsers You need to define one or stop calling it in your code.
Remove the event.preventDefault() from your code ande replace #submit="saveUser" with #submit.prevent="saveUser" in your form.
Import axios into your component with import axios from 'axios'. NOTE: Make sure axios ins installed in your project
I am trying to build a contact form in vue js and PHP but its not working and i am getting erros i used internet sources to build this form watched many tutorials i am not sure how to solve this. And i am very new to vuejs any kind of help would be appreciated
here's my code
<script>
export default{
data(){
return{
errorMessage: "",
successMessage: "",
errors: [],
trx_no: "",
name: "",
country: "",
email: "",
mobile_no: "",
myAddress: "",
newUser: {trx_no: "", name: "", country: "", email: "", mobile: ""}
}
},
mounted: function(){
this.getAllUsers();
},
myAddress: function() {
return this.$store.state.myAddress;
},
methods: {
saveUser: function(){
//console.log(this.newUser);
var formData = this.toFormData(this.newUser);
axios.post('http://localhost:8888/vue-and-php/public/api/update-info-form.php?action=update', formData, { crossdomain: true })
.then((response) => {
this.newUser = {trx_no: "", name: "", country: "", email: "", mobile: ""};
if(response.data.error){
this.errorMessage = response.data.message;
}else{
this.getAllUsers();
}
});
},
toFormData: function(obj){
var form_data = new FormData();
for(var key in obj){
form_data.append(key, obj[key]);
}
return form_data;
},
clearMessage: function(){
this.errorMessage = "";
this.successMessage = "";
},
//validation
checkForm: function (e) {
this.errors = [];
//if (!this.trx_no) {
// this.errors.push("TRX Address Required.");
//}
if (!this.name) {
this.errors.push("Name Required.");
}
if (!this.country) {
this.errors.push("Country Required.");
}
if (!this.email) {
this.errors.push('Email Required.');
} else if (!this.validEmail(this.email)) {
this.errors.push('Valid Email Address Required.');
}
if (!this.mobile_no) {
this.errors.push("Phone Number Required.");
}
if (!this.errors.length) {
return true;
}
e.preventDefault();
},
validEmail: function (email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
}
}
</script>
and this is the contact form
<template>
<b-container>
<div class="update-info">
<div class="feature-text myinv-title">
<h5 class="title title-sm">Update your information</h5>
</div>
<form
id="app"
#submit="checkForm"
method="post"
novalidate="true"
>
<p v-if="errors.length">
<b>Please fill in all the fields</b>
<ul>
<li v-for="error in errors" class="alert alert-danger">{{ error }}</li>
</ul>
</p>
<div class="form-row">
<div class="form-group col-md-3">
<label for="trx">TRX Address No.</label>
<input
id="trx"
class="form-control trx-address-nooverflow"
v-model="myAddress"
type="text"
name="TRX Address"
readonly
>
</div>
<div class="form-group col-md-3">
<label for="name">Name</label>
<input
id="name"
class="form-control"
v-model="name"
type="text"
name="name"
>
</div>
<div class="form-group col-md-3">
<label for="name">Country</label>
<country-select
id="Country"
class="form-control"
v-model="country"
:country="country"
topCountry="US" />
</div>
<div class="form-group col-md-3">
<label for="email">Email ID</label>
<input
id="email"
class="form-control"
v-model="email"
type="email"
name="email"
>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="email">Mobile No</label>
<input
id="mobile"
class="form-control"
v-model="mobile_no"
type="text"
name="mobile"
>
</div>
<div class="form-group col-md-3">
<div class="top-30">
<input type="submit" value="submit" class="btn btn-btn btn-grad btn-submit" #click="saveUser();"/>
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</b-container>
</template>
Thanks in advance and #respect
NOTE: API is working fine I've tested it in Postman
I don't know what errors you get, but I see a problem with how the form is submitted.
Some changes I recommend:
The form:
<form id="app" #submit="saveUser" method="post" novalidate="true"> ... </form>
The button:
<input type="submit" class="btn btn-btn btn-grad btn-submit" />
The saveUser method:
saveUser(event){
event.preventDefault()
this.checkForm()
if(!this.errors.length) {
var formData = this.toFormData(this.newUser);
axios.post('http...')
// rest of the code
}
}
Can't test it as I don't have the project, but this should help.
However, instead of the above approach, I would recommend to do the validation at input level and let each input component deal with its own validation logic and messages. The submit button to become enabled only when no errors exist in the form. There are many component libraries for this. For the user would be much better experience to see the errors in real time than with the above way to have a list of errors upon trying to submit the form.
DataSource gets json response data:
categoriesDS = new kendo.data.DataSource({
transport: {
read: {
url: "{{ path('get_json_categories') }}",
dataType: "json"
}
}
});
with white spaces:
{"categoryId":33,"parentId":32,"name":" [ ] p1"}
but rendering it without white spaces. How to change this behaviour?
edit: I need whitespaces in select options input. Below is my template script
<script id="popup_editor" type="text/x-kendo-template">
<form method="post" action="{{ path('updatedoc') }}" enctype="multipart/form-data">
<div class="k-edit-label">
<label for="documentFile">Plik</label>
</div>
<div data-container-for="documentFile" class="k-edit-field">
<input name="files" id="files" type="file" aria-label="files"/>
</div>
<input name="documentId" id="documentId" type="text" data-bind="value:documentId" style="display: none;"/>
<div class="k-edit-label">
<label for="documentDateAdd">Data Dodania</label>
</div>
<div class="k-edit-field">
<input type="text" class="k-input k-textbox k-state-disabled" name="documentDateAdd"
data-bind="value:documentDateAdd" disabled>
</div>
<div class="k-edit-label">
<label for="documentDesc">Opis</label>
</div>
<div data-container-for="documentDesc" class="k-edit-field">
<textarea name="documentDesc" class="k-textbox" data-bind="value:documentDesc"></textarea>
</div>
<div class="k-edit-label">
<label for="user">Twórca</label>
</div>
<div data-container-for="user" class="k-edit-field">
<input type="text" class="k-input k-textbox k-state-disabled" name="user" data-bind="value:user"
disabled>
</div>
<!-- dropdownlist-->
<div class="k-edit-label">
<label for="FacultyRankId">Kategoria</label>
</div>
<!-- dropdownlist editor for field: "FacultyRankId" -->
<div class="k-edit-field" id="categoriesDiv">
<input id="categoriesInput" name="categoryId"
{# tu wskazuję z którą wartością z data-source wiązać ten input tj z czym synchronizować, czyli
zmiany w inpucie na które pole ma wpływać z dataSource#}
data-bind="value:categoryId"
data-value-field="categoryId"
{#to co jest wyświetlane w dropdown#}
data-text-field="name"
data-source="categoriesDS"
data-role="dropdownlist"
data-value-primitive="true"
/>
</div>
<script type="text/javascript">
$('.k-edit-buttons:eq(1)').hide();
$("span.k-dropdown-wrap > span.k-input").each(function() {
console.log($(this).text());
var text = $(this).text().replace('PODKATEGORIA666, ', '. .');
$(this).text(text);
});
<\/script>
<div class="k-edit-buttons k-state-default">
<button type="submit" class="k-button k-primary"> Aktualizuj </button>
</div>
</form>
</script>
and style selector that didn't work:
<style>
input#categoriesInput { white-space: pre; }
</style>
(It looks like your post is mostly bar code; please add some more details.It looks like your post is mostly code; )
Try setting white-space style to pre and depending on the widget that you want to use it you will have to use different selectors.
Following an example for showing it in a drop down list:
<style>
span[aria-owns="color_listbox"] { white-space: pre; }
#color-list .k-item { white-space: pre; }
</style>
Following a snippet
$("#color").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [
{ text: " [ ] Black", value: "1" },
{ text: " [ ] Orange", value: "2" },
{ text: "Grey", value: "3" }
]
});
span[aria-owns="color_listbox"] {
white-space: pre;
}
#color-list .k-item {
white-space: pre;
}
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2018.1.221/styles/kendo.bootstrap-v4.min.css" />
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2018.1.221/js/kendo.all.min.js"></script>
<input id="color" value="1" style="width: 100%;" />
Please can some one point me in the right direction with this code.
When my form has been submitted a message is displayed however at the moment the Submit Button is still present.
I want to remove/hide the submit button once the form has been successfully submitted and the Success Message is being displayed.
I have looked around for answers on stack-overflow but so far everything I have tried has not worked.
Im sure I need to add something like this:
$('#sky-form button[type="submit"]').hide();
However I think maybe there is something already in the code that is stopping this from happening.
Here is my submit and message part of my form:
<button type="submit" button class="border-button">NEXT</button>
<div class="message">
<i class="fa fa-check"></i>
<p>Thanks for your order!<br>We'll contact you very soon.</p>
</form>
And here is the ajax:
submitHandler: function(form)
{
$(form).ajaxSubmit(
{
beforeSend: function()
{
$('#sky-form button[type="submit"]').addClass('button-uploading').attr('disabled', true);},
uploadProgress: function(event, position, total, percentComplete)
{
$("#sky-form .progress").text(percentComplete + '%');
},
success: function()
{
$("#sky-form").addClass('submited');
$('#sky-form button[type="submit"]').removeClass('button-uploading').attr('disabled', false);
}
});
},
Thanks so much to anyone that can help with this.
FULL CODE:
<form action="demo-order-process.php" method="post" enctype="multipart/form-data" id="sky-form" class="sky-form">
<fieldset>
<div class="row">
<div class="col-md-4" align="left">
<label class="input">
<input type="text" name="home_address" placeholder="Home Address">
<b class="tooltip tooltip-bottom-left">Enter your home address</b>
</label>
</div>
<div class="col-md-4" align="left">
<label class="input">
<input type="text" name="biz_address" placeholder="Biz Address">
<b class="tooltip tooltip-bottom-left">Enter your biz address</b>
</label>
</div>
</div><!-- END OF ROW DIV -->
</fieldset>
<!-- FORM ONE DATA -->
<input type="hidden" name="name"
value="<?php echo $_POST['name']; ?>">
<input type="hidden" name="email"
value="<?php echo $_POST['email']; ?>">
<!-- END OF FORM TWO DATA -->
<!-- FORM TWO DATA -->
<input type="hidden" name="mobile"
value="<?php echo $_POST['mobile']; ?>">
<input type="hidden" name="home"
value="<?php echo $_POST['home']; ?>">
<!-- END OF FORM TWO DATA -->
<div class="row">
<div class="col-md-4" align="left">
<button type="submit" button class="border-button">NEXT</button>
</div>
</div><!-- END OF ROW DIV -->
<div class="message">
<i class="fa fa-check"></i>
<p>Thanks for your order!<br>We'll contact you very soon.</p>
</div>
</form>
</div>
<!-- START OF JS VALIDATION -->
<script type="text/javascript">
$(function()
{
$("#sky-form").validate(
{
rules:
{
home_address:
{
required: true
},
biz_address:
{
required: true
},
messages:
{
home_address:
{
required: 'Please enter your home address'
},
biz_address:
{
required: 'Please enter your business address'
},
},
// Ajax form submition
submitHandler: function(form)
{
$(form).ajaxSubmit(
{
beforeSend: function()
{
$('#sky-form button[type="submit"]').addClass('button-uploading').attr('disabled', true);
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#sky-form .progress").text(percentComplete + '%');
},
success: function()
{
$("#sky-form").addClass('submited');
$('#sky-form button[type="submit"]').removeClass('button-uploading').attr('disabled', false);
}
});
},
errorPlacement: function(error, element)
{
error.insertAfter(element.parent());
}
});
});
</script>
<!-- END OF JS VALIDATION -->
JQuery Librarys:
`
<!-- fort forms -->
<script src="../form/jquery.min.js"></script>
<script src="../form/jquery-ui.min.js"></script>
<script src="../form/jquery.form.min.js"></script>
<script src="../form/jquery.validate.min.js"></script>
<!-- for page finctions -->
<!-- PROBLEM FILE = <script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>-->
<script type="text/javascript" src="../js/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
<script type="text/javascript" src="../js/jquery.mb.YTPlayer.min.js"></script>
<script type="text/javascript" src="../js/jquery.flexslider-min.js"></script>
<script type="text/javascript" src="../js/perfect-scrollbar.js"></script>
<script type="text/javascript" src="../js/plugins.js"></script>
<script type="text/javascript" src="../js/main.js"></script>`
I just tried this code and seems to be working.
If it did not work please check the error you are getting in console.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form action="demo-order-process.php" method="post" enctype="multipart/form-data" id="sky-form" class="sky-form">
<fieldset>
<div class="row">
<div class="col-md-4" align="left">
<label class="input">
<input type="text" name="home_address" placeholder="Home Address">
<b class="tooltip tooltip-bottom-left">Enter your home address</b>
</label>
</div>
<div class="col-md-4" align="left">
<label class="input">
<input type="text" name="biz_address" placeholder="Biz Address">
<b class="tooltip tooltip-bottom-left">Enter your biz address</b>
</label>
</div>
</div><!-- END OF ROW DIV -->
</fieldset>
<!-- FORM ONE DATA -->
<input type="hidden" name="name" value="<?php echo $_POST['name']; ?>">
<input type="hidden" name="email" value="<?php echo $_POST['email']; ?>">
<!-- END OF FORM TWO DATA -->
<!-- FORM TWO DATA -->
<input type="hidden" name="mobile" value="<?php echo $_POST['mobile']; ?>">
<input type="hidden" name="home" value="<?php echo $_POST['home']; ?>">
<!-- END OF FORM TWO DATA -->
<div class="row">
<div class="col-md-4" align="left">
<button type="submit" button class="border-button">NEXT</button>
</div>
</div><!-- END OF ROW DIV -->
<div class="message">
<i class="fa fa-check"></i>
<p>Thanks for your order!<br>We'll contact you very soon.</p>
</div>
</form>
<!-- START OF JS VALIDATION -->
<script type="text/javascript">
$(function()
{
$("#sky-form").validate({
rules:
{
home_address:
{
required: true
},
biz_address:
{
required: true
}
},
messages:
{
home_address:
{
required: 'Please enter your home address'
},
biz_address:
{
required: 'Please enter your business address'
},
},
// Ajax form submition
submitHandler: function(form) {
$(form).ajaxSubmit(
{
beforeSend: function()
{
$('#sky-form button[type="submit"]').addClass('button-uploading').attr('disabled', true);
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#sky-form .progress").text(percentComplete + '%');
},
success: function()
{
$("#sky-form").addClass('submited');
$('#sky-form button[type="submit"]').removeClass('button-uploading').attr('disabled', false);
$('#sky-form button[type="submit"]').hide();
}
});
},
errorPlacement: function(error, element)
{
error.insertAfter(element.parent());
}
});
});
</script>
<!-- END OF JS VALIDATION -->
I am trying to use jquery-validate plugin to validate a form inside a bootstrap-dialog. The "required" rule doesn't prevent me from submitting a form with an empty text field. However, "digits" rule works so that means validation is initialized properly. What am I missing here? Thanks.
Here's how I display the bootstrap-dialog and how I initialize validation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>App Title</title>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/bootstrap/3.0.3/bootstrap.min.css" />"></link>
<script src="<c:url value="/js/jquery/1.10.2/jquery-1.10.2.min.js" />"></script>
<script src="<c:url value="/js/jquery-ui/1.10.4/jquery-ui.min.js" />"></script>
<script src="<c:url value="/js/bootstrap/3.0.3/bootstrap.min.js" />"></script>
<script src="<c:url value="/js/bootstrap-dialog//bootstrap-dialog.min.js" />"></script>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/style.css" />"></link>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/jquery-ui/1.10.4/jquery-ui.min.css" />"></link>
<link type="text/css" rel="stylesheet" href="<c:url value="/css/bootstrap-dialog/bootstrap-dialog.min.css" />"></link>
<script src="<c:url value="/js/jquery-validation/1.11.1/jquery.validate.min.js" />"></script>
<script type="text/javascript">
function wireValidationEvent($form)
{
$form.validate({
errorElement: 'span',
errorClass: 'help-block',
wrapper: "div",
rules: {
name: {
required: true
}
},
messages: {
name: {
required: "Please enter the name properly."
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
}
function showModalDialog(url)
{
var get = $.get(url, '');
get.done(function(data) {
// Note that data contains just a form without any button.
// The form is dynamically injected into the body of the modal dialog. That's why wireValidationEvent() is called each time when a form is injected.
// When Save button is clicked, the form will be submitted using jquery.
BootstrapDialog.show({
title: 'Update Form',
closable: true,
autodestroy: true,
onshow: function(dialogRef){
var $body = dialogRef.getModalBody();
$body.append(data.trim());
var $formObj = $body.find('#formOfReligion');
if ($formObj)
{
// TODO bug: required validation rule doesn't work here
wireValidationEvent($formObj);
}
else
{
alert('formOfReligion is missing');
}
},
buttons: [{
label: 'Save',
action: function(dialog) {
var formObj = $('#formOfReligion');
if (formObj && formObj.length > 0)
{
var form = formObj[0];
var post = $.post(form.action, formObj.serialize());
post.done(function( data ) {
// succeeded
dialog.close();
$('#frmQuery').submit();
});
post.fail(function( data ) {
// failed
});
}
}
}, {
label: 'Cancel',
action: function(dialog) {
dialog.close();
}
}]
});
});
return true;
}
</script>
Here's what the modal dialog looks like.
<div class="modal-backdrop fade in"></div>
<div id="bea044b7-a0cb-48df-8b57-6cbdedac9bdf" class="modal fade bootstrap-dialog type-primary size-normal in" tabindex="-1" style="display: block;" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="bootstrap-dialog-header">
<div class="bootstrap-dialog-title">Update Form</div>
<div class="bootstrap-dialog-close-button" style="display: block;">
<button class="close">×</button>
</div>
</div>
</div>
<div class="modal-body">
<div class="bootstrap-dialog-body">
<div class="bootstrap-dialog-message"></div>
</div>
<form id="formOfReligion" class="form-horizontal" role="form" method="POST" action="/prs/protected/test" novalidate="novalidate">
<fieldset>
<div class="form-group">
<div>
<label class="control-label" for="name">Name</label>
</div>
<div>
<input id="id" type="hidden" value="6" name="id">
<input id="name" class="form-control" type="text" value="test" autofocus="autofocus" name="name">
</div>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
<div class="bootstrap-dialog-footer">
<div class="bootstrap-dialog-footer-buttons">
<button id="667d578f-490e-4d08-a8c1-1013b60c3394" class="btn btn-default">Save</button>
<button id="8b647389-edce-4f64-af8e-64521e865dcf" class="btn btn-default">Cancel</button>
</div>
</div>
<input id="id" type="hidden" value="6" name="id">
<input id="name" class="form-control" type="text" value="test" autofocus="autofocus" name="name">
You have a hard-coded value of "test" on the input so the required rule is already satisfied without the user having to enter anything.
BTW: I don't think you have a good naming system here: id="id", name="id", id="name", and name="name". It's not semantic, not scalable, and potentially confusing.