plugin doesn't show the modified messages - jQuery Validate plugin - javascript

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/

Related

combining 2 buttons into 1

I have 2 buttons on my form, one is a recaptcha submit button and the other is a submit button which validates the javascript against the form. I want 1 button to do both things but cannot figure it out. I tried moving the attrbiutes from the recaptcha button to the other submit button but this did not work. Google gave me a snippet of code and I cross referenced it with the original code and made some changes
Please note: in my code, where it says "my-site-key" I am actually using my recaptcha site key
can anybody help?
here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sales Inquiry || dontmissthebus.co.uk</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<link href="https://fonts.googleapis.com/css?family=Mukta+Mahee:300,700" rel="stylesheet">
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" />
<link rel="stylesheet" href="css/style.css" />
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("main-offer-form").submit();
}
</script>
</head>
<body>
<section class="bg-alt hero p-0">
<div class="container-fluid">
<div class="row">
<div class="col-sm-6 bg-faded text-center col-fixed">
<div class="vMiddle">
<h3 class="pt-4 h2">
<span class="text-green">dontmissthebus.co.uk</span>
<br>
<small>available for sale</small>
</h3>
<p class="mt-4">
To make an offer either fill out the form, or go to our main website
</p>
<!--
<div class="pt-5">
<label for="name">
<a class="btn text-white bg-green btn-lg">Buy now for $4999</a>
</label>
</div>
-->
<div class="row d-md-flex text-center justify-content-center text-primary action-icons">
<!--
<div class="col-sm-4">
<p><em class="ion-ios-telephone-outline icon-md"></em></p>
<p class="lead">+[Your Phone]</p>
</div>
<div class="col-sm-4">
<p><em class="ion-ios-chatbubble-outline icon-md"></em></p>
<p class="lead">email#[Your Domain].com</p>
</div>
-->
</div>
</div>
</div>
<div class="col-sm-6 offset-sm-6">
<section class="bg-alt">
<div class="container">
<div class="row height-100">
<div class="col-sm-10 offset-sm-1 mt-2">
<form id="main-offer-form" action="contact.php" method="post">
<h2 class="text-primary">Interested in this domain?</h2>
<hr/>
<div class="form-group">
<input
type="text"
name="name"
id="name"
class="form-control"
placeholder="Full name (Required)"
>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<input
type="email"
name="email"
class="form-control"
placeholder="Email (Required)"
>
</div>
</div>
<div class="col">
<div class="form-group">
<input
type="text"
name="phone"
class="form-control"
placeholder="Phone number (Required)"
>
</div>
</div>
</div>
<div class="form-group">
<input
type="number"
name="price"
class="form-control"
min="0"
placeholder="Offer price in GBP (Required)">
</div>
<div class="form-group">
<textarea name="comments" class="form-control" placeholder="Message (optional)"></textarea>
</div>
<div class="form-group">
<button class="g-recaptcha btn text-white btn-lg bg-primary btn-block" data-sitekey="my-site-key" data-callback='onSubmit'>Submit</button>
</div>
<button type="submit" class="btn text-white btn-lg bg-primary btn-block">Make an offer</button>
</form>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</section>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script>
$( "#main-offer-form" ).validate({
errorClass: 'form-control-feedback',
errorElement: 'div',
highlight: function(element) {
$(element).parents(".form-group").addClass("has-danger");
},
unhighlight: function(element) {
$(element).parents(".form-group").removeClass("has-danger");
},
rules: {
name: 'required',
email: {
required: true,
email: true
},
phone: {
required: true,
minlength:10,
maxlength:17
},
price: "required",
comments: {
maxlength: 500
}
},
messages: {
name: 'Please enter your name.',
email: {
required: 'You can not leave this empty.',
email: 'Please enter a valid email address.'
},
phone: {
required: 'You can not leave this empty.',
matches: 'Please enter a valide phone number.',
minlength: 'Phone number should be min 10 digits.',
maxlength: 'Phone number should be max 17 digits.'
},
price: {
price: 'Please enter offered price.'
},
comments: {
maxlength: 'Message length must be less than 500 character.'
}
}
});
</script>
</body>
</html>
You need to do this programmatically.
First remove all the data attributes on your button so that it doesn't add event listeners automatically.
Then update your onSubmit function to manually trigger the recaptcha validation like.
function onSubmit(e) {
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('my-site-key', {action: 'submit'})
.then(function(token) {
// manually submit the form from here
document.getElementById("main-offer-form").submit();
});
});
}
In case of such road blocks, always refer to the official documentation.

How to change only error message color of input form-control

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>

how to output field is required in the input form

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>

bootstrap validator submit handle

I am using bootstrap validator to validate my form created with bootstrap.
I have used the bootstrapValidator function to validate my form and also built in submitHandle of this function. In submitHandle, i am using simply post method as you can see.
major problem is I am not able to submit my form after clicking the submit button.You can also run code snippet and can see that after hitting submit button,it just stuck and then if I change any of the above field and then click submit again then it works fine. Not able to make it work on first attempt.
Not able to find bug....any help would be appreciated.
thanks!!
$(document).ready(
function() {
var validator = $("#registration-form").bootstrapValidator({
live: 'enabled',
feedbackIcons: {
//valid: 'glyphicon glyphicon-ok',
//invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
fname: {
message: "this field is required",
validators: {
notEmpty: {
message: "this field is required"
},
stringLength: {
max: 20,
message: "this field cannot be larger than 20 characters"
}
}
},
lname: {
message: "This field is required",
validators: {
notEmpty: {
message: "this field is required"
},
stringLength: {
max: 20,
message: "this field cannot be larger than 20 characters"
}
}
},
department: {
validators: {
greaterThan: {
value: 1,
message: "choose one department"
}
}
},
year: {
validators: {
greaterThan: {
value: 1,
message: "select your current year"
}
}
},
email: {
message: "Email address is required",
validators: {
notEmpty: {
message: "Please provide an email address"
},
emailAddress: {
message: "invalid email address"
}
}
}
},
submitHandler: function(validator, form, submitButton) {
$.ajax({
url: 'register.php',
type: 'post',
dataType: 'json',
data: $("#registration-form").serialize(),
success: function(data) {;
}
});
}
});
});
<!DOCTYPE html>
<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">
<title>Learning Boostrap</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/basic-template.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<!-- BootstrapValidator CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<!-- jQuery and Bootstrap JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js" type="text/javascript"></script>
<!-- BootstrapValidator -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/js/bootstrapValidator.min.js" type="text/javascript"></script>
</head>
<body>
<div class="row">
<div class="column col-md-6">
<div class="panel panel-default panel_custom">
<div class="panel-heading" style="background:linear-gradient(to left,black 70%,#300032); border:0px">Registration</div>
<div class="panel-body">
<form id="registration-form" method="POST" action="register.php" role="form">
<div class="form-group">
<label class="control-label" for="fname">name:</label>
<div class="row">
<div class="column col-md-6">
<input type="text" class="form-control" id="fname" name="fname" placeholder="First" />
</div>
<div class=" col-md-6">
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last" />
</div>
</div>
</div>
<div class="row">
<div class="column col-md-6">
<div class="form-group">
<label class="control-label" for="department" style="padding-top:10px">Department:</label>
<Select id="department" name="department" class="form-control" ">
<option value="0 ">choose one</option>
<option value="1 ">computer Science</option>
<option value="2 ">Bio medical science</option>
<option value="3 ">Instrumentaion</option>
<option value="4 ">Physics</option>
<option value="5 ">Polymer science</option>
<option value="6 ">Microbiology</option>
<option value="7 ">Food technology</option>
<option value="8 ">Electronics</option>
</select>
</div>
</div>
<div class="form-group ">
<div class="column col-md-6 " >
<label class="control-label " for="year " style="padding-top:10px ">Year:</label>
<Select id="year " name="year " class="form-control " ">
<option value="0">choose year</option>
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
<option value="4">4th</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="column col-md-6">
<div class="form-group">
<label class="control-label" for="male" style="padding-top:10px">Gender:</label>
<div class="radio">
<label>
<input type="radio" value="1" name="gender" required/>Male</label>
</div>
<div class="radio">
<label style="padding-left:20px">
<input type="radio" value="2" name="gender" />Female</label>
</div>
</div>
</div>
<div class="column col-md-6">
<div class="form-group">
<label class="control-label" for="email" style="padding-top:10px">E-mail Address:</label>
<input type="text" class="form-control" id="email" placeholder="Email Address" name="email" />
</div>
</div>
</div>
<div class="row">
<div class="column col-md-12">
<button class="btn btn-success" type="submit" value="but" name="submit">Submit</button>
</div>
</div>
</form>
<div id="confirmation" class="alert alert-success hidden" style="background:linear-gradient(to left,black 70%,#300032); border:none;">
<span class="glyphicon glyphicon-star"></span>
<h4>Thank you for registering. We will revert back shortly on email provided by you</h4>
</div>
</div>
</div>
</div>
</body>
</html>

JQuery mobile: how to validate the form and show error message on page

Hi i am new to JQM and i am trying to work on a JQM login page.
can any one help me how to do form validation and show the errors below the username and password text box if they are left empty and also when there is a invalid login i have to show it as an error message on top of the form.
here is my html:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="jquery.mobile/jquery.mobile-1.4.2.min.css" />
<script src="jquery.mobile/jquery.js"></script>
<script src="js/login1.4.2.js"></script>
<script src="jquery.mobile/jquery.mobile-1.4.2.min.js"></script>
</head>
<body>
<input type="hidden" id="session_key" />
<div data-role="page" id="login" class="" data-ajax="false">
<div data-role="header" >
<h3>Login Page</h3>
</div>
<div data-role="main" class="ui-content" >
<form id="check-user" data-ajax="false" class="ui-bar ui-bar-a ui-corner-all" >
<fieldset >
<div class="ui-field-contain" >
<label for="username" class="required">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password" />
</div>
<button class="ui-btn ui-shadow ui-corner-all ui-btn-b" name="submit" id="submit" value="submit">Submit</button>
</fieldset>
</form>
</div>
</div>
<div data-role="page" id="panel-main" >
<div data-role="header">
<h1>main panel</h1>
</div>
<div role="main" class="ui-content ">
<p>main panel</p>
</div>
</div>
</body>
</html>
Here is my JS file
$(document).on('pageinit', '#login', function() {
$("#submit").on("click",function(){
$.ajax({
url: "login_back.php",
type: "GET",
data: $("form#check-user").serialize(),
async: true,
callback: 'jsonLogin',
dataType:'jsonp',
success: function (result) {
if(result.status==true)
{
$('#session_key').val(result.session_key);
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#panel-main" );
}
else
{
alert("Wrong Username/Email and password combination");// here insted of alert i want to display it as error message in the form
}
},
error: function (request,error) {
alert('Network error has occurred please try again!'+error);
},
});
return false;
});
});
Simply combine jQuery validation plugin with jQuery Mobile.
Working example: http://jsfiddle.net/Gajotres/RLJHK/
HTML:
<div data-role="page" id="home" data-theme="b">
<form id="form1">
<div data-role="header">
<h2>Get Update</h2>
</div>
<div data-role="content">
<div data-role="fieldcontainer">
<label for="fname" data-theme="d">First Name:</label>
<input type="text" id="fname" name="fname" data-theme="d" placeholder="Enter First Name"/>
<br />
</div>
<div data-role="fieldcontainer">
<label for="lname" data-theme="d">Last Name:</label>
<input type="text" id="lname" name="lname" data-theme="d" placeholder="Enter Last Name"/>
</div>
<div data-role="fieldcontainer">
<label for="email" data-theme="d">E-mail Address:</label>
<input type="email" id="email" name="email" data-theme="d" placeholder="Enter Email"/>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div class="ui-grid-a">
<div class="ui-block-a">
<div class="ui-bar ui-bar-a">
<input type="button" data-icon="delete" value="Cancel" id="cancel"/>
</div>
</div>
<div class="ui-block-b">
<div class="ui-bar ui-bar-a">
<input type="submit" data-icon="check" value="Submit" id="submit"/>
</div>
</div>
</div>
</div>
</form>
</div>
<div data-role="page" id="success" data-theme="b">
<div data-role="header">
<h2>Thank You !!!</h2>
</div>
</div>
JavaScript:
$('#form1').validate({
rules: {
fname: {
required: true
},
lname: {
required: true
},
email: {
required: true
}
},
messages: {
fname: {
required: "Please enter your first name."
},
lname: {
required: "Please enter your last name."
},
lname: {
required: "Please enter your email."
}
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().prev());
},
submitHandler: function (form) {
$(':mobile-pagecontainer').pagecontainer('change', '#success', {
reload: false
});
return false;
}
});
CSS:
.error {
color:red;
}
If you want to find more about this topic take a look here.

Categories