I'm trying to use the jQuery Validate plugin in a view of a CodeIgniter project using exactly like a lot of examples Internet, but doesn't work at all! I used a lot of sugerences that I found here in StackOverflow and other sites, but doesn't work. Here is my code:
<script src="<?php echo base_url(); ?>js/jquery-validation-1.16.0/dist/jquery.validate.js"></script>
<body>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-md-6">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Ingresar nueva empresa</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form id="formIngEmpresa">
<!-- RESPUESTA DE FORMULARIO -->
<!-- FIN RESPUESTA DE FORMULARIO -->
<div class="box-body">
<div class="form-group">
<label for="usuario_login">Nombre o Razón Social de la empresa</label>
<input type="input" class="form-control" id="nm_rs_empresa" placeholder="Ingrese login">
</div>
<div class="form-group">
<label for="usuario_password">Rut empresa</label>
<input type="input" class="form-control" id="nr_rut_empresa" placeholder="rut">
</div>
<div class="form-group">
<label for="usuario_password2">Descripcion empresa</label>
<input type="text" class="form-control" id="nm_desc_empresa" placeholder="Password">
</div>
<div class="form-group">
<label for="usuario_nm_usuario">Rubro de la empresa</label>
<input type="input" class="form-control" id="nm_rubro" placeholder="Ingrese nombres">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Ingresar</button>
<button type="reset" class="btn btn-default">Cancelar</button>
</div>
</form>
</div>
<!-- /.box -->
</div>
<!-- /.row -->
</section>
</body>
<script>
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
alert($("#formIngEmpresa").validate().form());
$("#formIngEmpresa").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
nm_rs_empresa: "required",
nr_rut_empres: "required",
nm_desc_empresa: "required",
nm_rubro: "required"
},
// Specify validation error messages
messages: {
nm_rs_empresa: "Porfavor introducir nombre empresa",
nr_rut_empres: "Por favor introducir rut",
nm_desc_empresa: "Por favor introducir una Descripcion",
nm_rubro: "Elija el rubro de la empreesa",
},
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
$("#submit").click(function(){
$("#formIngEmpresa").submit();
return false;
});
});
</script>
jQuery Validate plugin doesn't work in CodeIgniter
Right, it doesn't. jQuery is JavaScript and it only works in the browser, while CodeIgniter only works on the server. In other words, your framework does not matter to JavaScript as long as you send the proper HTML markup to the browser.
Here's why you're having difficulties...
You must have a name attribute on every input considered for validation and these names must exactly match the names you used when you declared your rules. Even your code comments say the same thing!
rules: {
// The key name on the left side is the name attribute <-- READ HERE!!
// of an input field. Validation rules are defined
// on the right side
nm_rs_empresa: "required", // <- 'nm_rs_empresa' must match the 'name' attribute
....
The click handler could be bypassing the plugin. Since jQuery Validate automatically captures the click event of the submit button and fully takes care of the submission, you absolutely would not need any additional event handlers. Remove this entire click handler... it's not needed.
$("#submit").click(function() { // REMOVE THIS
$("#formIngEmpresa").submit(); // REMOVE THIS
return false; // REMOVE THIS
}); // REMOVE THIS
Working DEMO: jsfiddle.net/wtdhvtc7/
First update the ID of the form
Instead if this
<form id="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js">
put
<form id="formIngEmpresa">
This is your first mistake, the ID of form must match with the JQuery methods $("#formIngEmpres").validate() where formIngEmpres is the ID of the form.
Related
I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question
I have seen quite a few questions and answers on here but none seem to fix my issue. I have a form which is loaded from a ajax load call into a div class called dynamic-content. Basically if the form submit button is pressed I want it to reload this form in ajax so that it does the php form validation. My issue is that when the submit occurs I call the ajax load to reload via javascript but it is not triggering and instead its just going back to the current index page. My JS is as follows:
$(document).ready(function () {
//Handle AJAX request from sidebar buttons
var trigger = $('.submit-btn'),
container = $('.dynamic-content');
$(".add-customer-form-btn").submit(function() {
// do something...
alert('test');
container.load('customers/customersaddform.php',$("form").serializeArray());
return false;
});
});
my html form in customersaddform.php which is loaded into dynamic-content div in located main index file.
<?php
//FORM VALIDATION CHECKS
?>
<form action="" method="post">
<div class="form-field add-customer-form">
<div class="container-fluid">
<!-- Stack the columns on mobile by making one full-width and the other half-width -->
<h4>Account Information</h4>
<div class="row">
<div class="col-md-6 label-container">
<div class="input-group input-group-icon">
<input type="text" placeholder="First Name" name="first-name" required/>
<div class="input-icon"><i class="fa fa-user"></i></div>
<div class="input-error-msg"><?php echo $first_name_err;?></div>
</div>
</div>
<div class="row">
<div class=col-md-12 label-container">
<input type="submit" class="add-customer-form-btn submit-btn" value="Submit">
</div>
</div>
</div>
</div>
</form>
I have two forms on a page that are identical, but I'm trying to validate the one field (which is email in this case), but I can't seem to get it to just validate the one input field as it just shows the error for both forms.
HTML:
<div class="general-form">
<div class="email-error" style="display:none;">
<p>You need valid email</p>
</div>
<div class="form-wrap">
<div class="form-row">
<input id="from-email" type="email" name="email" placeholder="Your Email" />
</div>
<div class="btn-row">
<button class="submit-btn">Submit</button>
</div>
</div>
</div>
<div class="general-form">
<div class="email-error" style="display:none;">
<p>You need valid email</p>
</div>
<div class="form-wrap">
<div class="form-row">
<input id="from-email" type="email" name="email" placeholder="Your Email" />
</div>
<div class="btn-row">
<button class="submit-btn">Submit</button>
</div>
</div>
</div>
JS:
$(".submit-btn").on("click", function() {
var $this = $(this);
var valid_email = $this.find("#from-email").val();
if (/(.+)#(.+){2,}\.(.+){2,}/.test(valid_email)) {
return true;
} else {
$this.parents().find(".email-error").show();
return false;
}
});
Overall, I can get it to pass through the validation, but the error message shows for both forms and I'm not sure how to get it so it only shows the error message for that particular form. I'm guessing that I'm pushing too far up the chain and it's testing for both of the forms, but I can't remember which one to target specifically if that makes any sense.
You doubled the id from-email that’s why. In your JS you are checking all fields with the id from-email in this case both of the inputs are checked because both the id.
If one of them is wrong you are searching for the email-error in all of your parents which will go up to the body and then find all off the error wrappers. $this.parents(“.general-form“) will do the deal and only go up to the wrapper of the input and error in your case.
Always make sure your id’s are unique.
Just add required> attribute and add this js
$("#formid").validate();
I have a couple of input form items that I want to be shown when the user clicks a button. Here's the JSFiddle
So, I've created an html button and referenced my JS method when it's clicked:
<button type="button" id="mostrarOpcionesFiltrado" onclick="return mostrarFiltros.esconderFiltros();" class="btn btn-default btn-xs">Mostrar Opciones de Filtrado</button>
I've created a file formularios.js and added it to the bottom of my page:
<script src="js/formularios.js"></script>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
And finally created my JS file (formularios.js) where I take away the classes that maintain the items hidden:
var mostrarFiltros = {
esconderFiltros: function() {
if(document.getElementById('mostrarOpcionesFiltrado').clicked) {
console.log('mostrando las opciones de filtrado');
$('#apellido').removeClass('sr-only');
$('#email').removeClass('sr-only');
$('#dni').removeClass('sr-only');
$('#username').removeClass('sr-only');
}
},
} //cierre del objeto mostrarFiltros
And these are the parts of the form that should be affected by clicking the button:
<div id="apellido" class="form-group sr-only">
<label for="exampleInputName2">Apellido</label>
<input type="text" class="form-control" name="apellido">
</div>
<div id="email" class="form-group sr-only">
<label for="exampleInputName2">Email</label>
<input type="text" class="form-control" name="email">
</div>
<div id="dni" class="form-group sr-only">
<label for="exampleInputName2">DNI</label>
<input type="text" class="form-control" name="dni">
</div>
<div id="username" class="form-group sr-only">
<label for="exampleInputName2">UserName</label>
<input type="text" class="form-control" name="username">
</div>
My problem is that when I click the button, the console throws an error:
Uncaught ReferenceError: mostrarFiltros is not defined
What Am I doing wrong? Thanks!
Firstly, there are a few things wrong with yout jsFiddle (check the settings on your javascript section of jsFiddle):
your Javascript is defined "onLoad" so its not visible on the global scope.
You are using jQuery selectors, but haven't added jQuery in your frameworks and extensions.
Secondly, as another user mentioned, even if the function was defined, the actions you wish to have will not be executed because of your if statement.
Also, I would suggest you either
Stick to pure js https://jsfiddle.net/nd0vmtvz/ :
var mostrarFiltros = {
esconderFiltros: function() {
document.getElementById('apellido').classList.remove('sr-only');
document.getElementById('email').classList.remove('sr-only');
document.getElementById('dni').classList.remove('sr-only');
document.getElementById('username').classList.remove('sr-only');
},
}
or
Go with jQuery https://jsfiddle.net/q2xd65xc/ :
var mostrarFiltros = {
esconderFiltros: function() {
$('#apellido').removeClass('sr-only');
$('#email').removeClass('sr-only');
$('#dni').removeClass('sr-only');
$('#username').removeClass('sr-only');
},
} //cierre del objeto mostrarFiltros
$(function() {
$('#mostrarOpcionesFiltrado').click(function() {
mostrarFiltros.esconderFiltros();
});
})
Finally, to answer your original problem, the file containing your javascript is most likely not being loaded. You can verify this with devtools/firebug. It would be helpful if you posted your folder structure as well.
Are you still getting the ReferenceError or is it that code isn't doing what you want it to do. Once you get past the ReferenceError, the code won't work because you have this line:
if(document.getElementById('mostrarOpcionesFiltrado').clicked){
That condition will never be true so the code inside that condition won't work. See this jsFiddle for a working version: https://jsfiddle.net/bmuzy1py/4/
I don't know why I received this error when I changed the code to php (from html). when the extension of the file is html, the code is working fine.
<?php?>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="css/manual.css">
<!-- Optional theme -->
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<title>Register</title>
</head>
<body>
<nav class="navbar navbar-default" id="navBar">
</nav>
<div class="full">
<div class="col-xs-12">
<!--Side Bar-->
<div class="col-xs-3" id="navSide">
</div>
<div class="col-xs-6" id="signUpForm">
<h1>Register Page</h1>
<form role="form" id="signUpForm">
<div class="form-group">
<div class="form-inline spacer-12">
<input type="text" class="form-control" name="userFirstname" placeholder="First Name">
<input type="text" class="form-control" name="userLastName" placeholder="Last Name">
</div>
</div>
<div class="form-group ">
<input type="text" class="form-control"
name="userEmail"
placeholder="Email">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="userPassword" placeholder="Password">
</div>
<div class="form-group ">
<input type="password" class="form-control" name="confirmPassword" placeholder="Password">
</div>
<div class="form-group ">
<label> Birthday* </label>
<input type="date" class="form-control" name="userBirthday" placeholder="Birthday">
</div>
<input type="submit" class="btn btn-info spacer-12" style="clear:both" >
</form>
</div>
</div>
</div>
<script src="js/startup.js"></script>
<script src="js/signup.js"></script>
</body>
</html>
<?php?>
then this is my jquery validation code
$(document).ready(function(){
$('#signUpForm').validate({
errorElement: "span",
errorClass: "help-block",
rules:{
userFirstName:{
required: true
},
userLastName:{
required: true
},
userEmail:{
required: true
},
userPassword:{
required: true
},
confirmPassword:{
required: true
},
userBirthday:{
required: true
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error').addClass('red-border');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success').removeClass('red-border');
}
});
});
This code causes error when I click the submit button (JQuery Validate Uncaught TypeError: Cannot read property 'settings' of undefined )
But the error is temporary and will vanish in a while.
You defined two ids with same name, whereas id should be unique.
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
Try to remove id from <div class="col-xs-6" id="signUpForm">
If you use the rules() method, make sure to initialize the validation first.
var validator = $("#Form1").validate();
$('#field1').rules("add", {
min: 1
});
This error is normally caused by trying to validate an element that is not a form. In the OP's case, there are two elements with the same ID:
<div class="col-xs-6" id="signUpForm">
<form role="form" id="signUpForm">
jQuery searches a page from top to bottom, and the first element it finds with this ID is not a form.
The Validator.element() function (for validating single elements) can also cause this error, if attempting to validate an element that is outside the form.
NOTE two things
1. Define the Jquery function
include the function of jQuery !
(function( $ ) {
//Start Script
//endscript/
})( jQuery );
Change the Form Id because it's doing conflict between Form Id and Div Id
<form role="form" id="signUpForm1"> // include 1 in previous form id
And put this id into script
$('#signUpForm1').validate({ // put the Id in the script
Hope Your Task will be successful.
To add a small detail here, I ran into the same problem with jQuery UI time picker, and it also was due to the id being non-unique.
In my case, it's because I was grabbing the parent element from a template - duplicating it for a pop-up window. As a result, the contents of the window all had duplicate ids.
My normal workaround for that was to replace this:
$('#foo').bar();
with this:
myPopupWindow.find('#foo').bar();
That works quite well for most things, but not for the time picker. For that one, I wound up doing this:
myPopupWindow.find('#foo').attr('id', 'foo_' + someUniqueTag);
myPopupWindow.find('#foo_' + someUniqueTag).timepicker();
where someUniqueTag is a record id, random number or some other distinct string. This solved it quite nicely for me.