i want to output "field is required " or minlength error messages inside input box or placeholder with box color becoming red via jQuery . i have my form and validations work but message goes out underneath the boxes which looks ugly and make some disorder in the form .
my code :
<form action="" method="POST" id="login_form">
<div class="form-group has-feedback">
<input type="username" name="username" id="username" class="form-control" placeholder="username" ><span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" id= "password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat"name="login">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
jQuery code :
<script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form').validate({
rules: {
username: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 5
},
},
});
});
</script>
You can define your css for the .error class then detect on onkeyup for the input.error for removing the error label see code snippet :
$(document).ready(function() {
$('form').validate({
rules: {
username: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 5
},
},
});
$(document).on("keyup", "input.error", function(){
$("label[for='"+$(this).attr('id')+"']").hide();
});
});
.form-group {
position:relative;
}
label.error{
position:absolute;
top:0px;
left:0px;
background-color:#fff;
color:red;
}
input.error{
border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.js"></script>
<form action="" method="POST" id="login_form">
<div class="form-group has-feedback">
<input type="username" name="username" id="username" class="form-control" placeholder="username" ><span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" id= "password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat"name="login">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
Related
I am trying to style my first website.
I am using Bootstrap 4 and the jquery validation plugin and I am doing a form right now. I have two problems:
First, I only want to change the color of the error message below my input, but my styling changes the input text size/color and the error message text size/color, how can I only change error text below an input?
Second question is, where in my code do I change the Bootstrap form control state, depending on valid or not?
This is my code so far:
$('document').ready(function(){
$('#registration_form').validate({
rules: {
username: {
required: true,
maxlength: 10,
minlength: 3
},
email: {
required: true,
email: true
},
email_con: {
required: true,
equalTo: "#email"
},
password: {
required: true,
minlength: 7
},
password_con: {
required: true,
equalTo: "#password"
},
formCheck: {
required: true
},
}
});
});
.error{
color: red;
font-Size: 13px;
}
<div class="form-row form-group">
<div class="col-sm-4 col-xl-3 text-center d-xl-flex justify-content-xl-center align-items-xl-center label-column"><label class="col-form-label">Email* :</label></div>
<div class="col-sm-6 input-column"><input class="form-control" type="email" name="email" id="email" placeholder="name#mail.com"></div>
</div>
If you want to change color of error text message only then write like label.error{color: red;} and follow below html structure.
$(document).ready(function(){
$('#registration_form').validate({
rules: {
email: {
required: true,
email: true
}
}
});
});
label.error{
color: red;
font-size: 13px;
}
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<div class="container my-2">
<div class="row">
<form class="col-sm-12" action="#" id="registration_form">
<div class="form-row form-group">
<div class="col-sm-4 text-sm-right">
<label class="col-form-label" for="email">Email* :</label>
</div>
<div class="col-sm-6">
<input class="form-control" type="email" name="email" id="email" placeholder="name#mail.com">
</div>
</div>
<div class="form-row form-group">
<div class="col-sm-6 offset-sm-4">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
There are classes to deal with validaiton when it comes to bootstrap usage. Try like this
<div class="container">
<p class="h1">Register</p>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" class="form-control" id="email"
placeholder="E-mail" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
The e-mail is required!
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Password" required minlength="6">
<div class="valid-feedback">
Great!
</div>
<div class="invalid-feedback">
The password must contain at least 6 characters!
</div>
</div>
<div class="form-group mt-3">
<button class="btn btn-primary" type="submit">Register!</button>
</div>
</form>
</div>
<script>
(function() {
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
You can run a snippet in full page and check this answer
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<p class="h1">Register</p>
<form class="needs-validation" novalidate>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" class="form-control" id="email"
placeholder="E-mail" required>
<div class="valid-feedback">
Looks good!
</div>
<div class="invalid-feedback">
The e-mail is required!
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password"
placeholder="Password" required minlength="6">
<div class="valid-feedback">
Great!
</div>
<div class="invalid-feedback">
The password must contain at least 6 characters!
</div>
</div>
<div class="form-group mt-3">
<button class="btn btn-primary" type="submit">Register!</button>
</div>
</form>
</div>
<script>
(function() {
window.addEventListener('load', function() {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
</script>
In this code I need to validate modal after validation it should move to another modal
In jquery I have validated after successfully validated the data-target have been added in jquery code,but it does not working properly
fiddle link for the detailed view
after entering the values there is problem in jquery part because the email and text box have been validated
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<button class="main" data-toggle="modal" data-target="#myModalnew" data-dismiss="modal">Check</button>
<div class="modal_main">
<div class="modal fade" id="myModalnew" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Heading</h2>
<h4>Details</h4>
</div>
<div class="modal-body border">
<form id="contact" method="POST">
<fieldset>
<div class="input-group email">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input id="email" type="email" class="form-control" name="email" placeholder="Email">
</div>
<div class="input-group name">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="tab-content">
<div id="criteria_ship" class="tab-pane fade in active">
<div class="input-group address">
<span class="input-group-addon"><i class="glyphicon glyphicon-map-marker"></i></span>
<input id="address" type="text" class="form-control" placeholder="Street">
</div>
<div class="input-group town">
<input type="text" class="form-control" id="city" placeholder="City">
<input type="text" class="form-control" id="postcode" placeholder="Postcode">
</div>
<div class="paybutton">
<input type="submit" class="but_key but_link" id="pay" value="Payment" data-toggle="modal" data-target="#" data-dismiss=""
>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModalnew1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<
<h2 class="modal-title">getsmartnet.com</h2>
<h4>Smartnet's Payment</h4>
</div>
<div class="modal-body">
<form>
<fieldset>
<div class="main_card">
<div class="input-group card">
<span class="input-group-addon"><i class="glyphicon glyphicon-credit-card"></i></span>
<input id="card" type="text" class="form-control" placeholder="Card Number">
</div>
<div>
<div class="input-group date">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
<input type="text" class="form-control" id="expiry" placeholder="MM/YY">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="text" class="form-control" id="code" placeholder="CVC">
</div>
</div>
<div class="input-group check_rem">
<input type="checkbox" id="rem_check"> Remember Me
</div>
<fieldset id="main_rem">
<div class="input-group forgot"id="check_mobile">
<div class="input-group">
<span>For security, please enter your <strong><span>mobile phone number</span></strong>
</span>
</div>
<div class="input-group mob_rem">
<span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
<input type="tel" class="form-control" id="mob_num">
</div>
</div>
</fieldset>
<fieldset>
<div class="but_link">
Pay
</div>
</fieldset>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var name = $( "#name" ),
password = $( "#password" ),
street=$("#street"),
city=$("#city"),
pin=$("#postcode");
$('#pay').click(function(e) {
var isValid = true;
$('input[type="text"]').each(function() {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "1px solid red"
});
isValid = false;
}
else {
$(this).css({
"border": "",
"background": ""
});
isValid = true;
}
});
var email = $( "#email" ).val();
var check_em=false;
if ($.trim(email).length == 0) {
$("#email").css({
"border": "1px solid red"
});
check_em=false;
e.preventDefault();
}
else if (validateEmail(email)) {
$("#email").css({
"border": "",
"background": ""
});
check_em=true;
}
else {
$("#email").css({
"border": "1px solid red"
});
check_em=false;
e.preventDefault();
}
if(check_em==true && isValid==true){
alert("final");
$(this).attr('data-dismiss',"modal");
$(this).attr('data-target',"#myModalnew1");
}
});
});
function validateEmail(email) {
var filter = /^[a-zA-Z0-9]+#[a-zA-Z0-9]+.[a-z]{2,4}$/;
var res_tes=filter.test(email)
console.log(res_tes);
if (res_tes==true) {
return true;
}
else {
return false;
}
}
</script>
</body>
</html>
Your isValid was remaining false even after the validation was successful, so if(check_em==true && isValid==true) this was never true, and next modal was never triggered.
Here I fixed those issues, now it works
$(document).ready(function() {
var name = $("#name"),
password = $("#password"),
street = $("#street"),
city = $("#city"),
pin = $("#postcode");
$('#pay').click(function(e) {
//prevent form submission to server
e.preventDefault();
//set it to false initially
var isValid = false;
$('input[type="text"]').each(function() {
if ($.trim($(this).val()) === '') {
$(this).css({
"border": "1px solid red"
});
} else {
$(this).css({
"border": "",
"background": ""
});
// set it to true, only if it's valid
isValid = true;
}
});
var email = $("#email").val();
var check_em = false;
if ($.trim(email).length === 0) {
$("#email").css({
"border": "1px solid red"
});
check_em = false;
e.preventDefault();
} else if (validateEmail(email)) {
$("#email").css({
"border": "",
"background": ""
});
check_em = true;
} else {
$("#email").css({
"border": "1px solid red"
});
check_em = false;
e.preventDefault();
}
if (check_em && isValid) {
$(this).attr('data-dismiss', "modal");
$(this).attr('data-target', "#myModalnew1");
}
});
});
function validateEmail(email) {
var filter = /^[a-zA-Z0-9]+#[a-zA-Z0-9]+.[a-z]{2,4}$/;
return filter.test(email);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<button class="btn btn-primary main" data-toggle="modal" data-target="#myModalnew" data-dismiss="modal">Check</button>
<div class="modal_main">
<div class="modal fade" id="myModalnew" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Heading</h2>
<h4>Details</h4>
</div>
<div class="modal-body border">
<form id="contact" method="POST">
<fieldset>
<div class="input-group email">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input id="email" type="email" class="form-control" name="email" placeholder="Email">
</div>
<div class="input-group name">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="tab-content">
<div id="criteria_ship" class="tab-pane fade in active">
<div class="input-group address">
<span class="input-group-addon"><i class="glyphicon glyphicon-map-marker"></i></span>
<input id="address" type="text" class="form-control" placeholder="Street">
</div>
<div class="input-group town">
<input type="text" class="form-control" id="city" placeholder="City">
<input type="text" class="form-control" id="postcode" placeholder="Postcode">
</div>
<div class="paybutton">
<input type="submit" class="but_key but_link" id="pay" value="Payment" data-toggle="modal" data-target="#" data-dismiss=""
>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<div class="modal fade" id="myModalnew1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">getsmartnet.com</h2>
<h4>Smartnet's Payment</h4>
</div>
<div class="modal-body">
<form>
<fieldset>
<div class="main_card">
<div class="input-group card">
<span class="input-group-addon"><i class="glyphicon glyphicon-credit-card"></i></span>
<input id="card" type="text" class="form-control" placeholder="Card Number">
</div>
<div>
<div class="input-group date">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
<input type="text" class="form-control" id="expiry" placeholder="MM/YY">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input type="text" class="form-control" id="code" placeholder="CVC">
</div>
</div>
<div class="input-group check_rem">
<input type="checkbox" id="rem_check"> Remember Me
</div>
<fieldset id="main_rem">
<div class="input-group forgot"id="check_mobile">
<div class="input-group">
<span>For security, please enter your <strong><span>mobile phone number</span></strong>
</span>
</div>
<div class="input-group mob_rem">
<span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span>
<input type="tel" class="form-control" id="mob_num">
</div>
</div>
</fieldset>
<fieldset>
<div class="but_link">
Pay
</div>
</fieldset>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
jQuery validator doesn't recognize the messages that I set for the error. Could you help me?
This is my HTML document:
<!DOCTYPE html>
<html lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Subir cursos</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/jquery-ui.theme.css">
<link rel="stylesheet" href="css/jquery-ui.structure.css">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-8">
<ol class="breadcrumb">
<li>Inicio</li>
<li>Gestor</li>
<li class="active">Subir Curso</li>
</ol>
</div>
<div class="col-md-2">
<span class="glyphicon glyphicon-plus" aria-hidden="true"> Subir Catalogo
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3 class="text-center">
Subir curso
</h3>
</div>
</div>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<form role="form" enctype="multipart/form-data" method="post" id="curso" action="R/rCurso.php">
<p class="text-muted">Los campos marcados con (<span style="color:red">*</span>) son obligatorios</p>
<div class="form-group">
<label>Curso <span style="color:red">*</span></label>
<input class="form-control" id="ccrs" name="crs" type="text" required data-validation="length" pattern="/^[ A-Za-z0-9_#./#&+-]*$/"/>
</div>
<div class="form-group">
<label>Indice </label>
<textarea class="form-control" name="idx" id="cidx" ></textarea>
</div>
<div class="form-group">
<label>Descripcion</label>
<textarea class="form-control" name="dsr" id="cdsr" ></textarea>
</div>
<div class="form-group">
<label>Fecha <span style="color:red">*</span></label>
<input name="fch" type="text" id="datepicker" required/>
</div>
<div class="form-group">
<label>Idioma <span style="color:red">*</span></label>
<select id="languaje" name="lng" required>
</select>
</div>
<div class="form-group">
<label>Imágen <span style="color:red">*</span></label>
<input id="imgPick" name="imgPick" value="" type="hidden">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#sel">Seleccionar Imagen</a></li>
<li><a data-toggle="tab" href="#upload">Subir imagen</a></li>
</ul>
<div class="tab-content">
<div id="sel" class="tab-pane fade in active">
<h3>Selecciona una Imagen </h3>
<div class="row">
<div class="col-xs-12 col-md-12" id="pickimg">
</div>
</div>
</div>
<div id="upload" class="tab-pane fade">
<h3>Subir Imagen</h3>
<input id="exampleInputFile" name="input_field_name" type="file" />
<p class="help-block">
Solo archivos png, jpg, y jpeg de 600x600px
</p>
</div>
</div>
</div>
<div class="form-group">
<label>Enlace Youtube <span style="color:red">*</span></label>
<input class="form-control" name="url1" id="curl1" type="text" required/>
</div>
<div class="form-group">
<label>Enlace Vimeo</label>
<input class="form-control" name="url2" id="curl2" type="text" />
</div>
<div class="form-group">
<label>Enlace DailyMotion</label>
<input class="form-control" name="url3" id="curl3" type="text" />
</div>
<div class="form-group">
<label>Nivel <span style="color:red">*</span></label>
<select name="lvl" id="clvl" required>
<option value="1">Superior</option>
<option value="2">Medio Superior</option>
</select>
</div>
<div class="form-group">
<label>Palabras clave <span style="color:red">*</span></label>
<input class="form-control" name="key" id="ckey" type="text" required/>
</div>
<div class="form-group">
<label>Autor <span style="color:red">*</span></label>
<select name="idAuth" id="idAuth" required>
</select>
</div>
<div class="form-group"><script src="js/jquery.js"></script>
<label>Escuela <span style="color:red">*</span></label>
<select name="idEscu" id="idEscu" required>
</select>
</div>
<div class="form-group">
<label>Categoria <span style="color:red">*</span></label>
<select id="catg" name="idCatg" required>
</select>
</div>
<div class="form-group">
<label>Subcategoria <span style="color:red">*</span></label>
<select id="subCat" name="idSubctg" required>
</select>
</div>
<button type="submit" id="save" class="btn btn-default">
Enviar
</button>
</form>
</div>
<div class="col-md-3">
</div>
</div>
</div>
<script src="js/webService.js"></script>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery-validate.js"></script>
And this is the Script part where I have to set the messages right?, I did but then when I test, I get the default error message that is
This field is required.
here the script part, tell me if other functions make that the code works like that or if I did something wrong
$(document).ready(inicio);
function inicio() {
$(function () {
$("#datepicker").datepicker();
});
$( "#curso" ).validate( {
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
this.element(element);
}
},
rules: {
ccrs: {
required: true,
minlength: 10
},
cidx: {
minlength: 10
},
cdsr: {
minlength: 10
},
datepicker: {
required: true,
date: true
},
languaje: {
required: true
},
curl1: {
required: true,
url: true
},
curl2: {
url: true
},
curl3: {
url: true
}
},
messages: {
ccrs: {
required:"Please enter your firstname",
minlength:"el minimo es 10"},
cidx: {
minlength:"your test must have more than 10 characters"},
cdsr: {
minlength:"your test must have more than 10 characters"},
datepicker: {
required: "Please set a date",
date: "It must be a Date"
},
languaje: {
required: "Please set any language"
},
curl1: {
required:"Please enter a valid email address",
url: "you must set an url"}
}
} );
var autores = "#" + $('#idAuth').attr('id');
var escuelas = "#" + $('#idEscu').attr('id');
var categorias = "#" + $("#catg").attr('id');
var subcategorias = "#" + $('#subCat').attr('id');
var idiomas = "#" + $('#languaje').attr('id');
listAutores(autores);
listEscuelas(escuelas);
listCategorias(categorias);
listIdiomas(idiomas);
$(categorias).one(function () {
listSubcategorias(subcategorias, $(this).val());
});
$(categorias).on("change", function () {
listSubcategorias(subcategorias, $(this).val());
});
listImgCursos("#pickimg");
}//inicio
Within .validate(), you've mixed up the id with the name...
rules: {
ccrs: { // <- must match the NAME, not the ID!
required: true,
minlength: 10
},
....
},
messages: {
ccrs: { // <- must match the NAME, not the ID!
required: "Please enter your firstname",
minlength: "el minimo es 10"
},
....
For simplicity, just make the id and name the same.
<input id="ccrs" name="ccrs" type="text" ....
The only reason validation was still working was because you set some HTML5 validation attributes inline. For example, required was only working because you had the required attribute inline (that's also why you saw the default message).
BTW, there is no need to have inline HTML5 validation attributes when you properly declare the rules within the .validate() method. Remember, the jQuery Validate plugin will dynamically disable HTML5 validation, so certain HTML5 attributes will be picked up and used by jQuery Validate, while others will be ignored.
DEMO: jsfiddle.net/psr9grq7/3/
I can't seem to get validation to work on my bootstrap modal, I have struggled with several of the examples that I have encountered.
What is the correct way to validate a bootstrap modal?
My HTML:
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form class="form-control" role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control required error" id="pName" name="pName" placeholder="Enter a p name" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" placeholder="Enter and action">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My Javascript:
$(function () {
$("#newModalForm").validate({
rules: {
pName: {
required: true,
minlength: 8
},
action: "required"
},
messages: {
pName: {
required: "Please enter some data",
minlength: "Your data must be at least 8 characters"
},
action: "Please provide some data"
}
});
});
Based upon my code nothing appears to happen when I click the save button on modal. I am utilizing the jquery.validate.js script.
Can someone point me in the right direction?
You have two issues:
You're button needs to be set to type="submit" not type="button"
Your submit button should be inside your form tag.
See working example Snippet.
$(function() {
$("#newModalForm").validate({
rules: {
pName: {
required: true,
minlength: 8
},
action: "required"
},
messages: {
pName: {
required: "Please enter some data",
minlength: "Your data must be at least 8 characters"
},
action: "Please provide some data"
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name" require/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action" require>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
If you need send data via AJAX from bootstrap modal use following code:
$("#addMyModal form").validate({
rules: {
Name: {
required: true,
minlength: 2
},
Email: {
required: true,
minlength: 5
},
Phone: {
required: true,
minlength: 12
}
},
messages: {
Name: {
required: "Обязательное поле",
minlength: "Минимальная длинна Имени 2 символа"
},
Email: {
required: "Обязательное поле",
minlength: "Минимальная длинна Email 5 символов",
email: "Пожалуйста введите корректный email адрес."
},
Phone: {
required: "Обязательное поле",
minlength: "Минимальная длинна Телефона 11 символов"
}
},
submitHandler: function(form) {
$.ajax({
url: './pay-vip.php',
type: 'POST',
data: $(form).serialize(),
success: function(response) {
location.replace(location + "pay-vip.php");
alert("Send mail")
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name" require/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action" require>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
I had some similar problem. But it turned out that
$("#newModalForm").validate({ ... });
has to be put outside the
$(function () { });
This fixed my issue
I'm using PHP, jQuery, Smarty, etc. for my website.
I've one form on which there are three input text fields viz. zip_code, city and state. I've written jQuery code to auto-populate the city and state input text fields when user enters valid US zip code into input text field zip_code.
Other jQuery functionality on the form is working fine and perfect but I'm having issue only with this functionality. I created one demo page for this functionality there this zip_code functionality worked properly. But it's not working in my project.
I'm putting below the whole HTML of the page which contains the form :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Project Name</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Example of Fixed Layout with Twitter Bootstrap version 2.0 from w3resource.com">
<meta name="author" content="">
<link href="http://localhost/project_folder/user_ui_files/css/bootstrap.css" rel="stylesheet">
<link href="http://localhost/project_folder/user_ui_files/css/example-fixed-layout.css" rel="stylesheet">
<link href="http://localhost/project_folder/user_ui_files/css/bootstrap-responsive.css" rel="stylesheet">
<link href="http://localhost/project_folder/user_ui_files/css/bootstrap-modal.css" rel="stylesheet">
<link href="http://localhost/project_folder/user_ui_files/css/slippry.css" rel="stylesheet">
<link href="http://localhost/project_folder/user_ui_files/css/signin.css" rel="stylesheet" type="text/css">
<link href="http://localhost/project_folder/user_ui_files/css/jquery.dateLists.css" rel="stylesheet" type="text/css">
<style type="text/css">
.hideme {
opacity:0;
}
#media (max-width: 979px) {
.navbar-fixed-top.navbar-absolute {
position: absolute;
margin: 0;
}
}
.navbar-absolute + div {
margin-top: 58px;
}
#footer {
position: absolute;
bottom: 0;
width: 100%;
/* Set the fixed height of the footer here */
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div class="navbar navbar-fixed-top navbar-absolute">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="http://localhost/project_folder/index.php"><img src="http://localhost/project_folder/user_ui_files/img/logo.png"/></a>
<div class="nav-collapse">
<ul class="nav pull-right navbar-fixed-bottom">
<li><i class="icon-user icon-black"></i> LOGIN</li>
<li><i class="icon-pencil icon-black"></i> REGISTER</li>
<li><i class="icon-edit icon-black"></i> REBATE STATUS</li>
<li><i class="icon-envelope icon-black"></i> CONTACT</li>
<li><i class="icon-map-marker icon-black"></i> STORE LOCATOR</li>
<li>
<form action="index.php" class="navbar-form pull-right" id="formzip" method="post">
<input type="hidden" class="form-control" name="op" id="op" value="zip_code">
<input type="hidden" class="form-control" name="form_submitted" id="form_submitted" value="yes">
<input style="width: 115px;" type="text" placeholder="Enter the zip code" name="zip_code" id="zip_code" value="" > <i class="icon-zip" style="margin-top:3px;" onclick='$("#formzip").submit();'></i>
</form>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<style type="text/css">
.list {
width:60px;
}
.dateLists_container {
}
.dateLists_container .list {
float:left;
}
.dateLists_container .day_container {
}
.dateLists_container .day_container .list {
margin-right:10px;
}
.dateLists_container .month_container {
}
.dateLists_container .month_container .list {
margin-right:10px;
}
.dateLists_container .year_container {
}
.dateLists_container .year_container .list {
}
</style>
<div class="container" style="padding-top: 140px; margin-bottom: 90px;">
<div class="row">
<div class="span12 account-container12">
<legend>New User? Register</legend>
<form action="register.php" class="form-horizontal" method="post">
<div class="row">
<input type="hidden" class="form-control" name="op" id="op" value="preview">
<input type="hidden" class="form-control" name="form_submitted" id="form_submitted" value="yes">
<input type="hidden" class="form-control" name="main_op" id="main_op" value="">
<div class="col-xs-1"></div>
</div>
<div class="span6">
<div style="float: clear;"></div>
<fieldset>
<!-- Form Name -->
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="First Name">First Name<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="first_name" id="first_name" value="" type="text" placeholder="Enter your first name">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Last Name">Last Name<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="last_name" id="last_name" value="" type="text" placeholder="Enter your last name">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Street 1">Address 1<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="street1" id="street1" value="" type="text" placeholder="Enter the address">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Street 2">Address 2</label>
<div class="controls">
<input name="street2" id="street2" value="" type="text" placeholder="Enter your address">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Zip">Zip<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="zip_code" id="zip_code" value="" type="text" placeholder="Enter your zip code" class="input-medium">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="City">City<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="city" id="city" value="" readonly="readonly" type="text" placeholder="Select your city" class="input-medium">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="State Code">State<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="state_code" id="state_code" value="" readonly="readonly" type="text" placeholder="Enter state code" class="input-medium">
</div>
</div>
</fieldset>
</div>
<div class="span5">
<fieldset>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="DOB">Date Of Birth<span style="color:#FF0000">*</span></label>
<div class="controls">
<input class="form-control date_control" type="text" name="dob" id="dob" value="">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Email Id">Email Id<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="email" id="email" value="" type="text" placeholder="Enter your mail ID">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="num">Phone No.</label>
<div class="controls">
<input name="phone_no" id="phone_no" value="" type="text" placeholder="Enter phone no." class="input-medium">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Password">Password<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="password" id="password" value="" type="password" placeholder="Enter the Password" class="input-medium">
</div>
</div>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="Password">Confirm Password<span style="color:#FF0000">*</span></label>
<div class="controls">
<input name="password_confirmation" id="password_confirmation" value="" type="password" placeholder="Re-enter the password" class="input-medium">
</div>
</div>
<!-- Multiple Radios -->
<div class="control-group">
<label class="control-label" for="radios">Mode of Payment</label>
<div class="controls">
<label class="radio" for="radios-0">
<input type="radio" name="mode_of_payment" value="paypal">
PayPal
</label>
<label class="radio" for="radios-1">
<input type="radio" name="mode_of_payment" value="check">
Check
</label>
</div>
</div>
<!-- Text input-->
<div id="paypal_op" style="display:none;" class="control-group">
<label class="control-label" for="email">PayPal Email Account</label>
<div class="controls">
<input type="text" name="pay_pal_email" id="pay_pal_email" value="" placeholder="Enter email id" class="input-large">
</div>
</div>
</fieldset>
</div>
<div class="container">
<div class="row">
<div class="span2"></div>
<div class="span5">
<button type="submit" class="btn btn-success"><i class="icon-white icon-ok"></i> Preview</a>
</div>
</div>
</div>
</form>
</div>
</div>
</div> <!-- /container -->
<footer style="background-color:#000" id="footer">
<div class="container">
<div class="row">
<div class="span3 top-buffer-footer">
<p> © 2014 PROJECT NAME</p>
</div>
<div align="center" class="span7 top-buffer-footer">
About Us |
Privacy Policy |
Terms & Conditions
</div>
<div class="span2 top-buffer-footer">
<a style="float:right" href="#">Powered By COMPANY NAME</a>
</div>
</div>
</div>
</footer>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster and more quicker-->
<script src="http://localhost/project_folder/user_ui_files/js/jquery.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/slippry.min.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-tooltip.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-alert.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-button.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-carousel.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-collapse.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-dropdown.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-modal.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-popover.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-scrollspy.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-tab.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-transition.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-typeahead.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/bootstrap-modalmanager.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/jquery.dateLists.min.js"></script>
<script src="http://localhost/project_folder/user_ui_files/js/custom/common.js"></script>
</body>
</html>
The jQuery code to run this zip code functionality is written into file common.js which is included at last of this page.
Following is the code from the file common.js:
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i) {
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > (bottom_of_object - (bottom_of_object * 0.2)) ) {
$(this).animate({'opacity':'1'},300);
}
});
});
/*jQuery code for autopo-populate city and state when customer enters valid zip code*/
$("#zip_code").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city").val(result.city);
$("#state_code").val(result.state);
}
});
}
});
$('#dob').dateDropDowns({dateFormat:'mm-dd-yy'});
$("input[type='radio']").change(function() {
if($(this).val()=="paypal") {
$("#paypal_op").show();
} else {
$("#paypal_op").hide();
}
});
});
$(function() {
var demo1 = $("#demo1").slippry({
transition: 'fade',
useCSS: true,
speed: 1000,
pause: $('#brand_slider_time').val() * 1000,
auto: true,
preload: 'visible'
});
$('.stop').click(function () {
demo1.stopAuto();
});
$('.start').click(function () {
demo1.startAuto();
});
$('.prev').click(function () {
demo1.goToPrevSlide();
return false;
});
$('.next').click(function () {
demo1.goToNextSlide();
return false;
});
$('.reset').click(function () {
demo1.destroySlider();
return false;
});
$('.reload').click(function () {
demo1.reloadSlider();
return false;
});
$('.init').click(function () {
demo1 = $("#demo1").slippry();
return false;
});
});
I'm using jQuery v1.7.1 in my project.
I've also created a jsFiddle with only these necessary fields it's working fine. You can see the fiddle here.
In my project I tried to debug the code, tried to put alert inside the function I wrote for zip_code. Neither the Firebug console shown me any error nor the alert got printed.
Then I tried to print the alert outside the zip_code function (i.e. on page load) it printed. The alert is not getting printed inside the function. Also I tried various other events like focus, blur, etc. instead of key up then also the alert didn't print. The Firebug console never shown me any error or warning.
The markup in your post includes two form elements, one in what appears to be a navigation menu and another in what appears to be the main content of the page. Both these forms have an input element with the id zip_code.
In HTML id attributes are meant to be unique. For this reason, the expression $('#zip_code') would return only the first of the two elements with that id - the one in the navigation menu. This in turn causes the keyup event to not be bound to the second (and relevant) input field.
The reason it works in your fiddle is that the HTML in the fiddle does not include the navigation menu and therefore the markup includes only a single input element with the zip_code id.