I do have a html form which takes username and password as input . On button click , wrote a js function which would hit the api asynchronously . Before that , how would i validate it
<form>
<div><label id="resultString"></label></div>
<fieldset>
<legend>Login</legend>
Username: <input type="text" id="username"><br><br>
Password: <input type="password" id="password"><br><br>
<input type="button" onclick="submitdetails();" value="Login">
</fieldset>
</form>
My js function is :
function submitdetails() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var params = JSON.stringify({ username: username, password: password });
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200)
document.getElementById("resultString").innerHTML = xmlhttp.responseText;
else
document.getElementById("resultString").innerHTML = "Error";
}
};
xmlhttp.open("POST","http://127.0.0.1:8000/login/",true);
xmlhttp.send(params);
}
<form id='form' name='form' method='post' action=''>
<div><label id="resultString"></label></div>
<fieldset>
<legend>Login</legend>
Username: <input type="text" id="username" name="username"><br><br>
Password: <input type="password" id="password" name="password"><br><br>
<input type="button" value="Login">
</fieldset>
</form>
And this is the validator plugin code:
$(document).ready(function() {
$('#form').validate({
rules: {
username: {
required: true
},
password: {
required: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
success: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
}
});
});
refer: https://jqueryvalidation.org/
DEMO
THINGS TO REMEMBER
Your form should have a name and id
I say, give name and id for all fields as well
Use submit handler to do the call you did on onclick
<script>
function submitdetails() {
var username = $("#username").val();
var password = $("#passwords").val();
if(username==""||password=="")
{
alert("please fill");
}
var params = JSON.stringify({ username: username, password: password });
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200)
document.getElementById("resultString").innerHTML = xmlhttp.responseText;
else
document.getElementById("resultString").innerHTML = "Error";
}
};
xmlhttp.open("POST","http://127.0.0.1:8000/login/",true);
xmlhttp.send(params);
}
using following conditions
if(username ==null || username =="")
{
document.getEelementById("showerr").innerHTML = "is empty";
}
if(password==null || password =="" password.length < 6)
{
document.getEelementById("showerr").innerHTML = "must 6 or above characters";
}
HTML :
<span id="showerr"></span>
using regular expression you can validate
http://jsfiddle.net/ghvj4gy9/embedded/result,js/
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["email"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.email.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<br/>
email: <input type="text" name="email">
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
But its easy to use use jQuery validate plugin
Demo : https://jqueryvalidation.org/files/demo/
Documentation : https://jqueryvalidation.org/documentation/
sample code -
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
Related
I have a form that requires user to enter their digital signature before signing up. It looks like below:
So prior to signing up, user MUST enter their signature on the canvas box provided. I use jquery validation to validate my other fields before coming to this final page for signature.
I can validate all the fields except for the signature field. Any idea what I can do?
<div class="row">
<div class="col-12 col-md-8 offset-md-2 pl-3 pr-3 pt-2 mb-0">
<canvas class="display-block signature-pad" style="touch-action: none;"></canvas>
<p id="signatureError" name="signatureError" style="color: red; display: none;">Please provide your signature.</p>
<div class="p-1 text-right">
<button id="resetSignature" class="btn btn-sm" style="background-color: lightblue;">Reset</button>
<button id="saveSignature" class="btn btn-sm" style="background-color: #fbcc34;">Save</button>
</div>
<input type="hidden" name="signature" id="signatureInput">
</div>
</div>
<div class="row">
<div class="col-12 mb-0 pt-2">
<div class="text-right">
<input type="hidden" name="registrationFor" value="customer">
<button type="submit" id="submit" class=" btn next-button bjsh-btn-gradient text-right">Sign Up</button>
</div>
</div>
</div>
var canvas = document.querySelector("canvas");
const signatureSaveButton = document.getElementById("saveSignature");
const signatureResetButton = document.getElementById("resetSignature");
const signatureError = document.getElementById("signatureError");
const signatureInput = document.getElementById("signatureInput");
// Initialize a new signaturePad instance.
var signaturePad = new SignaturePad(canvas);
// Clear signature pad.
signatureResetButton.addEventListener("click", function(event) {
signaturePad.clear();
});
// Save signature pad as data url.
signatureSaveButton.addEventListener("click", function(event) {
if (signaturePad.isEmpty()) {
signatureError.style.display = "block";
} else {
signatureUrl = signaturePad.toDataURL();
signatureInput.value = signatureUrl;
}
});
// Validate registration tab before moving to the next tab
$("#register-form").validate({
rules: {
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
},
password: {
required: true,
minlength: 8,
},
password_confirmation: {
required: true,
minlength: 8,
equalTo: "#password"
},
full_name: {
required: true
},
nric: {
required: true
},
address_1: {
required: true
},
address_2: {
required: true
},
address_3: {
required: true
},
postcode: {
required: true
},
city: {
required: true
},
state: {
required: true
},
contact_number_home: {
required: true
},
contact_number_mobile: {
required: true
},
existing_customer: {
required: true
},
signatureError: {
required: true
},
},
messages: {
email: {
required: "Please enter an email",
email: "The email is not valid"
},
password: {
required: "Please enter a password",
minlength: "Password must be minimum of 8 characters"
},
password_confirmation: {
required: "Please confirm your password",
minlength: "Passmust must be minimum of 8 characters",
equalTo: "Password must be same as above"
},
full_name: {
required: "Please enter your full name"
},
nric: {
required: "Please enter your identity card number"
},
address_1: {
required: "Please enter your address"
},
address_2: {
required: "Please enter your address"
},
address_3: {
required: "Please enter your address"
},
postcode: {
required: "Please enter your postcode"
},
city: {
required: "Please select your city"
},
state: {
required: "Please select your state"
},
contact_number_home: {
required: "Please enter your home number"
},
contact_number_mobile: {
required: "Please enter your mobile number"
},
signatureError: {
required: "Please provide your signature"
},
}
});
// validate fields in 1st tab
$('#next-btn').click(function() {
if ($("#register-form").validate().element('#email') && $("#register-form").validate().element('#password') && $("#register-form").validate().element('#password-confirm')) {
nextTab.find('a').trigger('click');
} else {}
});
// validate fields in 2nd tab
$('#next-btn2').click(function() {
if ($("#register-form").validate().element('#full_name') && $("#register-form").validate().element('#nric') && $("#register-form").validate().element('#address_1') && $("#register-form").validate().element('#address_2') && $("#register-form").validate().element('#address_3') && $("#register-form").validate().element('#postcode') &&
$("#register-form").validate().element('#city') && $("#register-form").validate().element('#state') && $("#register-form").validate().element('#contact_number_home') &&
$("#register-form").validate().element('#contact_number_mobile') && $("#register-form").validate().element('#existing_customer')
) {
nextTab.find('a').trigger('click');
} else {}
});
// validate signature input in 3rd tab
$('#submit').click(function() {
if ($("#register-form").validate().element('#signatureError')) {
alert("Success");
} else {
alert("Failure");
}
});
If you are using signature_pad by Szymon Nowak then it looks like you set it up correctly.
Edit: OK, I got the signature field to be part of validation. You need to not ignore hidden fields.
Do not validate the error message, LOL. Validate the actual field.
Also, I added a custom validator to handle validating the signature pad, but since it sets the value of the hidden signature field when you hit save, we only need to validate the signature.
Helpful links
https://jqueryvalidation.org/documentation/
https://www.sitepoint.com/basic-jquery-form-validation-tutorial/
jQuery Validate - Enable validation for hidden fields
Example
let $form = $("#register-form");
let canvas = document.querySelector('.signature-pad');
let signatureSaveButton = document.getElementById('saveSignature');
let signatureResetButton = document.getElementById('resetSignature');
let signatureInput = document.querySelector('input[name="signature"]');
// Initialize a new signaturePad instance.
let signaturePad = new SignaturePad(canvas);
// Clear signature pad.
signatureResetButton.addEventListener('click', function(event) {
signaturePad.clear();
signatureInput.value = '';
event.preventDefault();
return false; // prevent submission...
});
// Save signature pad as data url.
signatureSaveButton.addEventListener('click', function(event) {
let signatureBlank = signaturePad.isEmpty();
if (!signatureBlank) {
signatureUrl = signaturePad.toDataURL();
signatureInput.value = signatureUrl;
$("div.error-messages span").html(''); // Clear messages
}
$(signatureInput).valid(); // Call validation on the field after hitting "Save"
event.preventDefault();
return false; // prevent submission...
});
// Not used, because this field has no name. Also, we want to use this
// to set the underlying (hidden) signature field...
$.validator.addMethod('signaturePresent', function(value, element) {
console.log('Checking...');
return this.optional(element) || signaturePad.isEmpty();
}, "Please provide your signature...");
// Validate registration tab before moving to the next tab
$form.validate({
ignore: [], // This is important! We want to validate hidden fields.
rules: {
signature: {
required: true
}
},
messages: {
signature: {
required: "Please provide your signature"
}
},
submitHandler: function(form) {
$("div.error-messages span").html(''); // Clear messages
console.log('Submitting form...');
//form.submit(); <-- UNCOMMENT TO ACTUALLY SUBMIT
},
invalidHandler: function(event, validator) {
console.log('INVALID!');
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error-messages span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
});
body {
padding: 2em;
}
.signature-pad {
display: block;
border: thin solid grey;
margin: 0 auto;
margin-bottom: 0.5em;
}
.hidden {
display: none !important;
}
form .error {
color: #F00;
}
.error-messages {
text-align: center;
font-size: smaller;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/1.5.3/signature_pad.min.js"></script>
<form id="register-form">
<div class="row">
<div class="col-md-6 text-center">
<label for="signatureInput">Signature</label>
</div>
<div class="form-group text-center">
<canvas class="display-block signature-pad" style="touch-action: none;"></canvas>
<div>
<button id="resetSignature" class="btn btn-sm" style="background-color: lightblue;">Reset</button>
<button id="saveSignature" class="btn btn-sm" style="background-color: #fbcc34;">Save</button>
</div>
<input type="hidden" name="signature" id="signatureInput">
</div>
</div>
<div class="row">
<div class="col-md-6 text-right">
<input type="hidden" name="registrationFor" value="customer">
<button type="submit" id="submit" class=" btn next-button bjsh-btn-gradient text-right">Sign Up</button>
</div>
</div>
</form>
<div class="error-messages"><strong>Messages:</strong><br/><span></span></div>
I have basic html and want to validate the fields with jQuery validator so I have less validation on php level. The form validates if all fields are empty and prevents submission to php but as soon as I complete 1 input the form sumits (even if all other fields are blank). All fields are required so I'm stumped - please help!
After some of your advice I have redone my validation on php level but it has the exact same effect. If all the fields are empty the validation works, as soon as 1 field is filled in the form submits.
jQuery: I ran it through JSLint and it yielded no errors - unbelievable right?!
$().ready(function () {
"use strict";
$('#register').validate({
rules: {
firstname: {
required: true,
maxLength: 40
},
lastname: {
required: true,
maxLength: 40
},
email: {
required: true,
maxLength: 64,
email: true
},
password: {
required: true,
minLength: 6,
maxLength: 32
},
confirmPassword: {
required: true,
equalTo: "#password"
},
rsaid: {
required: true,
digits: true
}
},
messages: {
firstname: {
required: "Please enter your first name.",
maxLength: "Your first name cannot exceed 40 characters."
},
lastname: {
required: "Please enter your last name.",
maxLength: "Your last name cannot exceed 40 characters."
},
email: {
required: "Please enter your email address.",
maxLength: "Your email address cannot exceed 64 characters.",
email: "The email format provided is invalid."
},
password: {
required: "Please enter a password.",
minLength: "Your password must contain at least 6 characters.",
maxLength: "Your password cannot contain more than 32 characters."
},
confirmPassword: {
required: "Please confirm your password.",
equalTo: "Your passwords do not match!"
},
rsaid: {
required: "Please enter a valid RSA id number.",
//exactLength: "Your ID number must contain 13 characters!",
digits: "Your ID number must consist of numerals only!"
}
},
errorContainer: $('#errorContainer'),
errorLabelContainer: $('#errorContainer ul'),
wrapper: 'li'
});
});
html: Shouldn't be necessary but just in case :)
<div class="registrationForm">
<form id="register" action="php/insert.php" method="post">
<input type="text" id="firstname" name="firstname" placeholder="First Name" value="" class="radius mini" />
<input type="text" id="lastname" name="lastname" placeholder="Last Name" value="" class="radius mini"/>
<input type="text" id="email" name="email" placeholder="Your Email" value="" class="radius" />
<input type="password" id="password" name="password" placeholder="New Password" value="" class="radius" />
<input type="password" id="confirmPassword" name="confirmPassword" placeholder="Confirm Password" value="" class="radius" />
<input type="text" id="rsaid" name="rsaid" placeholder="RSA ID Number" value="" class="radius" />
<button class="radius title" name="signup">Sign Up for SFC</button>
</form>
</div>
PHP code: This contains code for only the first 3 fields as password validation is long and irrelevant. The code returns no errors on phpcodechekcer.com.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameErr = "First name is required";
} else {
$firstname = mysqli_real_escape_string($link, $_POST['firstname']);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last name is required";
} else {
$lastname = mysqli_real_escape_string($link, $_POST['lastname']);
}
if (empty($_POST["email"])) {
$emailErr = "Email address is required";
} else {
if (!isValidEmail($_POST["email"])) {
$emailErr = "Email address is invalid";
} else {
$email = mysqli_real_escape_string($link, $_POST['email']);
}
}
}
better make validation on server side, if your client turn off javascript on browser then all data will send to server without any validation
It's to be need jquery file link on header of html.
Perhaps it's because you are not using fieldset enclosing?
On the other side, you may look towards plain HYML5 validation.
These are the text fileds for entering minimum and maximum text values.
<input type="text" name="min_rent" id="min_rent" placeholder="Min Rent" pattern="[0-9]+" style="width:75px" maxlength="15" required />
<input type="text" name="max_rent" id="max_rent" placeholder="Max Rent" style="width:75px;" pattern="[0-9]+" maxlength="15" onkeydown="check()" required />
And this is the submit button
<input type="submit" name="continue1" id="continue1" value="Submit" style="margin-left:10px;"/>
and form tag line
<form action="<?php echo site_url().'/customer_varad/rent_in_success';?>" name="frm" id="frm" method="post" onsubmit="check_validation();">
and these are my jquery validations
<script>
function check()
{
var un = $('#min_rent').val();
var un1 = $('#max_rent').val();
if(un>=un1)
{
$('#msg').html('Please Enter Maxmum Rent').show();
}else{
$('#msg').html('').hide();
}
}
</script>
function check_validation()
{
var un2 = $('#min_rent').val();
var un3 = $('#max_rent').val();
if(un2>=un3)
{
$('#msg').html('Please Enter Maxmum Rent').show();
}else{
$('#msg').html('').hide();
}
}
if(!$('#frm').valid()){
alert('Please Fill Mandatory Fields');
$(".div-personal").fadeIn();
$("#li-personal").animate({opacity:1});
return false;
}
if($('#frm').valid()){ alert('Details Are Entered Successfully!');
//$(".div-property-details").fadeIn();
return true;
}
}
$('#r_type').change(function(){
if ($('#r_type').val() == "2" || $('#r_type').val() == "3" || $('#r_type').val() == "4" || $('#r_type').val() == "5" || $('#r_type').val() == "8" || $('#r_type').val() == "10" || $('#r_type').val() == "14" ) {
$('#floor').hide();
} else {
$('#floor').show();
}
});
var un = $('#min_rent').val();
if(!un && un.length <= 0){
isValid = false;
$('#msg_min_rent').html('Please Select Minimum Rent').show();
}else{
$('#msg_min_rent').html('').hide();
}
//validate max Rent
var un1 = $('#max_rent').val();
if(!un1 && un1.length <= 0){
isValid = false;
$('#msg_max_rent').html('Please Select Maximum Rent').show();
}else{
$('#msg_max_rent').html('').hide();
}
</script>
what more do I add to the code and how do I arrange and place the function check so that along with rest of the validation I can even check minimum and maximum value validation
and this is my rule statements code
<script type="text/javascript">
$('#frm').validate({
rules:
{
uname:{required:true},
one_contact: { required: true,minlength:10,maxlength:10},
prop_location:{required: true},
per_city:{required: true},
//alt_contact: { required: true,minlength:10,maxlength:10},
//pre_address: {required: true},
//parman_address: {required: true},
//member:{required:true},
//dob: {required: true},
email_id:{required:true, email:true},
organization: {required: true},
r_type:{required:true},
location:{required:true},
city:{required:true}
// desig: {required: true},
//org_contact: {required: true,minlength:10,maxlength:10}
},
messages:
{
uname:{required:'Enter Name'},
one_contact: {required: 'Enter Mobile No',minlength : 'Minimum 10 Characters', maxlength : 'Maximum 10 Characters'},
prop_location:{required:'Select Location'},
per_city:{required:'Select City'},// alt_contact: {required: 'Please Insert Mobile No',minlength : ' Mobile No Minimum 10 Characters ',maxlength : ' Mobile No Maximum 10 Bharacters '},
// pre_address: {required: 'Enter Present Address'},
//parman_address: {required: 'Enter parmanant Address'},
// member:{required:'Enter family member'},
// dob: {required:'Enter Date of Birth'},
email_id:{required:'Enter Email Address'},
organization: {required: 'Enter Organization Name'},
r_type: {required:'Select Requirement Type'},
location: {required:'Select Location'},
city: {required:'Select City'}
// desig: {required: 'Enter Designation'},
// org_contact: {required: 'Please Insert Organisation Mobile No',minlength : ' Mobile No Minimum 10 Characters ',maxlength : ' Mobile No Maximum 10 Bharacters '}
}
});
</script>
even help out to work with the rules how they would be written.
Thank in advance.
I'm trying to submit my form through Jquery, but the submit part of my code just doesn't work! And I can't see what's wrong with it.
<?php
if(!isset($_SESSION["useridentity"])){
die(header("Location:index.php"));
}
include("actions/connect.php");
$q = "SELECT username FROM users WHERE useridentity = '".$_SESSION["useridentity"]."'";
$r = mysql_query($q,$con);
$f = mysql_fetch_array($r);
?>
<div class="absolutedialog" id="login">
<form class="loginform" id="loginform" name="loginform" method="POST" action="actions/login.php">
<div class="label">
Welcome back, <b><?php echo $f["username"]; ?></b>. Please, type your password to confirm your identity.
</div>
<input class="loginformpassword" id="password" type="password" name="pass" maxlength="32"/>
<div id="passwordfail"></div>
<input class="regularbutton" id="submit" type="button" value="Submit"/>
<button class="grayregularbutton" id="gobacktoconsole" type="button">Go back</button>
</form>
</div>
<div class="blackoverlay"></div>
<script>
$(document).ready(function() {
$('#login').fadeIn(1000);
$('.blackoverlay').fadeIn(500);
//Destroy $_SESSION variables and go back to console
$('#gobacktoconsole').on('click',this, function(e) {
$(".absolutedialog").fadeOut(500);
$(".blackoverlay").fadeOut(1000);
window.setTimeout(
function() {
window.location.href="actions/logout.php";
},
1000
);
});
//Submit validations
$('#submit').on('click',this, function(e){
if($("#password").val() == "")
$("#passwordfail").html("Please, type your password");
else{
$("form#loginform").submit();
$(".absolutedialog").fadeOut(500);
$(".blackoverlay").fadeOut(1000);
}
});
//Clear password message error when something is typed in the password input
$('#password').on('keyup',this, function(e) {
$("#passwordfail").html("");
});
//Prevent default submit on enter, and click #submit button instead in order to execute validations
$('#loginform').bind("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if(code == 13){
e.preventDefault();
$("#submit").click();
}
});
});
</script>
I tried adding return false; below $("form#loginform").submit(); but doesn't works. Am I missing something? Please, help!
Sorry for the lack of details; if you need me to add some more, please ask.
You have this element:
<input class="regularbutton" id="submit" type="button" value="Submit"/>
When you say
$("form#loginform").submit();
THe brpwser is assuming you're calling it, not the submit() method of the form object. Just change the id to something else.
<input class="regularbutton" id="submitButton" type="button" value="Submit"/>
The nastiest thing ever! Hope this helps.
I have seen many times problems about form submitting and form validation and I have found that the best way to do it is by using a simple open source jquery plugin such as jquery.validate.js.
This is an example about preventing default submit and posting data successfully to php file.
First you have to get these open source framework and you can use them whenever you want.
Files are three scripts :
<script src="js/jquery.min.js></script>
<script src="js/bootstrap.min.js"></script> <!-- open source framework twitter bootstrap -->
and one css file :
<link href="bootstrap/bootstrap.min.css" rel="stylesheet" media="screen">
example of code :
<form method="post" action="php/inscriptionAction2.php" class="form-horizontal" name="register" id="register">
// code of site inscription : name , email , password , confirmed password ....
<div class="form-group">
<div class="col-xs-offset-3 col-xs-9">
<div class="form-actions">
<input type="submit" class="btn btn-primary" name="newsubmit" id="newsubmit" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
</div>
</div>
</form>
and this is a simple script
$(document).ready(function(){
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
});
$('#loginForm').validate({
rules: {
name: {
minlength: 2,
lettersonly:true,
required: true
},
lname: {
minlength: 2,
lettersonly:true,
required: true
},
username: {
lettersonly:true,
minlength: 2,
required: true
},
email: {
required: true,
email: true,
remote: {
url: '/setup/verify_email/',
cache: false
}
},
password: {
required: true,
minlength: 5,
maxlength: 250
},
password2: {
equalTo: '#password'
},
gender: {
required: true
}
},
messages: {
name: {
required:"Please enter your first name",
minlenght:"Your first name must consist of at least {0} characters",
lettersonly: "Letters only please"
},
lname: {
required:"Please enter your last name",
minlenght:"Your last name must consist of at least {0} characters",
lettersonly: "Letters only please"
},
username: {
lettersonly: "Letters only please",
required: "Please enter a username",
minlength: "Your username must consist of at least {0} characters"
},
email: {
required:"Please enter your email address",
email:"Please enter a valid email adress",
url:"Please enter a valid url",
cache:""
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least {0} characters long",
maxlength: "Your password must be less than {0} characters long"
},
password2: {
equalTo: "Please enter the same passwords"
},
postal_code: "Please enter a valid zip code",
timezones: "Please select a time zone",
mp: "Please enter a valid mobile number. Only numbers please.",
gender: "Please select a gender",
dob: "Please enter a valid Date of Birth in mm/dd/yyyy format."
},
highlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).closest('.control-group').removeClass('error').addClass('success');
},
success: function (label) {
$(label).closest('form').find('.valid').removeClass("invalid");
},
errorPlacement: function (error, element) {
element.closest('.control-group').find('.help-block').html(error.text());
}
}).cancelSubmit=true; // to block the submit of this plugin and call submit to php file
By using two powerful frameworks, Twitter Bootstrap and jQuery , you can make your work faster and more professional.
For more details you can have a look at their documentation.
First you should import jquery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
second change the id value of the button to anything else and will work, you may need to set timeout before submitting in order to delay the submit after the fadeout effect
I'm trying to override the default message in jquery validation message I did as the documentation told but no use it is still show "This field is required." ?
http://jsfiddle.net/7Yrz7/
$(function () {
$('form').validate({
rules: {
email:"required",
password:"required",
messages: {
email: "Please enter an email address.",
password: "This field is required."
}
}
});
});
It should be:
$("form").validate({
rules: {
email: "required",
password: "required"
}, // <-- here
messages: {
email: "Please enter an email address.",
password: "This field is required."
}
});
You need to close the rules before using messages here.
Updated Fiddle
For using Validate plugin you have to add Rule first and then message.
The Scripts
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}, // end of rules
messages: {
field1: "You cannot leave field1 blank",
field2: "You cannot leave field1 blank"
}// end of message
});
});
The HTML
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension