I want to validate password and confirm password in HTML5. By using function required I have validated for empty value. But not able to validate password and confirm password
HTML:
<form id="registration" name="registration" action="registrationaction.php" method="POST">
<input type="password" class="agent-input registerinput" name="pswd" id="pswd">
<input type="password" class="agent-input registerinput " name="confirmpassword" id="confirmpassword">
</form>
JavaScript:
<script>
$().ready(function()
{
$("#registration").validate({
rules: pswd: {
required: true
},
confirmpassword: {
required: true
},
},
messages
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password",
},
submitHandler: function() { $('#registration').submit(); }
});
});
There are several methods to confirm the two password match. However, assuming you want to utilize the jQuery Validation Plugin (which your question seems to use), changing your Javascript code to this will do the job:
$().ready(function(){
$("#registration").validate({
rules: {
pswd: {
required: true
},
confirmpassword: {
required: true,
equalTo: "#pswd"
}
},
messages: {
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password"
},
submitHandler: function() { $('#registration').submit(); }
});
});
I should point out that your Javascript example had several issues (unclosed brackets, etc). They've been corrected in the example above.
And for more amazingness you can create with jQuery Validation Plugin, definitely remember to see their documentation webpage for an easy-to-read list of available options.
P.S.
To everyone insisting that $().ready() must be changed, I'd like to point out that it is perfectly valid syntax according to the jQuery documentation (although not recommended, it is valid).
You should write your code within proper ready() function. I think the code you have provided must be throwing errors. Anyhow two correct ways to do this would be:
$( document ).ready(function() {
//your code comes here
});
$(function() {
//your code comes here
});
Inside these you can write the form validation code. Please be clear on the point that you can only do this with JavaScript.
$(document).ready(function() {
$("#registration").validate({
rules: pswd: {
required: true
},
confirmpassword: {
required: true
},
},
messages
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password",
},
submitHandler: function() { $('#registration').submit(); }
});
});
OR
$(function() {
$("#registration").validate({
rules: pswd: {
required: true
},
confirmpassword: {
required: true
},
},
messages
pswd: "Please enter password",
confirmpassword: "Please enter valid confirm password",
},
submitHandler: function() { $('#registration').submit(); }
});
});
both function $(document).ready(function() { // code here }); and $(function() { // code here }); are equivalent. Don't forget to code for server side validation!!!
Related
Below is my javascript code. As you have noticed, in my $("#register-form").validate the rules are all the same, which is required:true . since it's just that, I wanted to make it required in their input fields instead in the html. I did try it, therefore I deleted the entire code inside the comment /* validation */ and added required in each of their input fields in my html form, but when I submit the form, it just reloads the page, not giving me the messages I was expecting in my function submitForm(). But if I use the entire code, it is submitting the form and gives me the correct alert message. So how will I disregard the rules and messages here? Since I already have required in my html input fields?
$('document').ready(function()
{
/* validation */
$("#register-form").validate({
rules:
{
firstname: {
required: true
},
lastname: {
required: true
},
username: {
required: true,
minlength: 8
},
password: {
required: true,
minlength: 8
},
password2: {
required: true,
equalTo: '#password'
},
email: {
required: true,
email: true
},
answer: {
required: true
},
},
messages:
{
firstname:"Please input your firstname.",
lastname:"Please input your lastname.",
answer:"Please input your answer.",
username:{
required: "Please input your username.",
minlength: "Username must be atleast 8 characters"
},
password:{
required: "Please input your password",
minlength: "Password must be atleast 8 characters"
},
email: "Please enter a valid email address",
password2:{
required: "Please re-type your password",
equalTo: "Password do not match!"
}
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#register-form").serialize();
$.ajax({
type : 'POST',
url : 'signup.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
},
success : function(data)
{
if(data==2){
$("#error").fadeIn(1000, function(){
alert('Email is already taken.');
document.getElementById ("email").focus();
});
}
else if(data==1){
$("#error").fadeIn(1000, function(){
alert('Username is already taken.');
document.getElementById ("username").focus();
});
}
else if(data==3)
{
alert('Registration successfully submitted.');
window.location='index.php';
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> Create Account');
});
}
}
});
return false;
}
/* form submit */
});
Well you are using a plugin to validate your input and it calls the submitHandler function when tests pass. So if you want to get rid of that validation you need to bind your submitForm function to a submit event...
$('document')
.ready(function () {
/* form submit */
function submitForm() {
//do stuff and return false
return false;
}
/* form submit */
$("#register-form").on("submit",submitForm);
});
I need to validate another ready made bad words filter after validating first rules (blank fields). I have all codes in ready made, someone please help me to add this second validation in my page.
This is my jquery codes where I need to include the 2nd validation.
$(function() {
$("#review").focus(function() {
$("#comments").removeClass('hide')
});
$("#sky-form").validate({
rules: {
digits: {
required: true,
digits: true
},
name: {
required: true
}
},
messages: {
digits: {
required: 'Please enter a valid amount of Money'
},
name: {
required: 'Please enter your username',
}
},
submitHandler: function(g) {
$(g).ajaxSubmit({
beforeSend: function() {
$('#sky-form button[type="submit"]').attr('disabled', true)
},
success: function() {success funtion goes here}
This is the 2nd validation codes that I need to include on top. Mainly I need this function - bwords=badwords(textbox_val); - It will verify bad word's after blank fields is okay.
<script language="javascript" type="text/javascript">
function Message()
{
var textbox_val=document.form.textbox.value;
if(textbox_val=="")
{
alert("Please enter a message");
return false;
}
bwords=badwords(textbox_val);
if(bwords>0)
{
alert("Your message contains inappropriate words. Please clean up your message.");
document.form.textbox.focus();
return false;
}
}
</script>
Those both function is working but I just need to include both validation like 2nd one in the top first script.
Sorry for my bad Enlgish.
You can add a new rule in your code. I called this rule badWords and for me the
bad word is BAD so when you try to type BAD in the name field you will get the
validation error message.
$.validator.addMethod("badWords", function(value, element) {
if (value.trim().length == 0) {
return false;
}
if (value == 'BAD') {
return false;
}
return true;
}, "BAD WORD");
$(function () {
$("#sky-form").validate({
rules: {
digits: {
required: true,
digits: true
},
name: {
required: true,
badWords: true
}
},
messages: {
digits: {
required: 'Please enter a valid amount of Money'
},
name: {
required: 'Please enter your username',
}
}
});
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<form id="sky-form">
<label for="ele1">Digits:</label>
<input type="text" id="ele1" name="digits"/>
<br/>
<label for="ele2">Name:</label>
<input type="text" id="ele2" name="name"/>
<br/>
<input type="submit" id="submit"/>
</form>
I have two forms: one for adding a new user and the other for user data modification.
Forms are basically the same, only difference is that when doing modification username field should not be checked if exists in database.
In Js file I do field validations. One of those validations is checking if username already exists in database. In modification this should not be considered.
This is why I thought this, but it's not working:
I differentiate the two forms with div id.
(view snippet add_user form):
<div id="add_user">
<form action="{site_url()}admin/updateFrontUser" id="form_sample_2" class="form-horizontal" method="post">
(view snippet edit_user form):
<div id="edit_user">
<form action="{site_url()}admin/updateFrontUser" id="form_sample_2" class="form-horizontal" method="post">
and then:
(js file snippet)
var algo = $('.add_user', form2);
form2.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
username: {
required: true,
minlength: 2,
maxlength: 15,
pattern: "[A-z](([\._\-][A-z0-9])|[A-z0-9])*[a-z0-9_]*",
remote: {
data: function(){
if (algo) {
url: '/admin/checkUsername';
type: 'POST';
};
}
}
},
The remote rule it's supposed to check if username exists. That function is already built in my admin.php. It worked previously, before I made the modifications I mentioned.
So to resume, How do I do just to use remote rule only for a new user (I mean, when using add form) ?
Please Try below rule
$().ready(function() {
$("#id_frm").validate({
rules: {
"id_question": {
required: true
},
"id_number": {
required: function(){ return $('input:radio[name=id_question]:checked').val() == 'Yes' },
minlength: 10,
minlength: 10
},
"contact_method": {
required: function(){ return $('input:radio[name=id_question]:checked').val() == 'No' }
}
},
messages: {
"id_question": {
required: "Please choose if you have an ID or not."
},
"id_number": {
required: "Please Enter ID."
},
"contact_method": {
required: "Please choose a contact method."
}
},
});
});
Can someone help me understand why onkeyup validation is not working? I have been staring at it too long! Thanks.
JSFiddle here.
Code:
$(document).ready(function () {
jQuery('#DSH0000000146FF').validate({
rules: {
dish_name: {
required: true
},
dish_description: {
required: true
}
},
messages: {
dish_name: {
required: "Please enter a name, no longer than 80 characters."
},
dish_description: {
required: "Please enter a description, no longer than 240 characters."
}
},
submitHandler: function (form) {
if(jQuery('#DSH0000000146FF').validate()){
alert("SUBMITTED!");
}
else{
}
}
});
});
Add submit button to form
<textarea id="DSH0000000146d" name="dish_description"
class="textarea-comment dish_description" maxlength="240">More testing
</textarea><br/>
<input type="submit"></input> <!-- Add this line -->
jsfiddle
UPDATE
Thanks to charlietfl's comments and suggestions (and, at one point ire, lol - apologies for my faux pas), I've finally got the system checking from within Validate, and the form submission is halted when the email is sent. So I guess my question is answered, but if you'll all bear with me for one more moment, there's one last finishing touch that I could use your help with...
In my original vision, in addition to triggering a proper "Email already exists" error, I also populated a second element with some HTML that more completely explained the situation to the user and provided a link to a login form. This second element appeared and disappeared depending on the status of the field.
Is there a way to use the messages/remote section to do this as well?
Here what I have:
$(document).ready(function(){
$("#signup").validate({
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.prev());
//element.prev().replaceWith(error);
},
rules: {
"email": {
required: true,
email:true,
remote: {
url: "/ajax/emailcheck.php",
type: "post",
},
},
"password": {
required: true,
minlength: 8,
},
"password-check": {
required: true,
minlength: 8,
passmatch: true,
},
"tos": {
required: true,
minlength: 6,
}
},
messages: {
email: {
required: " is Required",
email: " is Improperly Formatted",
remote: " already exists",
},
},
password: {
required: " is Required",
minlength: " requires at least 8 characters",
},
"password-check": {
required: " is Required",
minlength: " requires at least 8 characters",
passmatch: " must match the Passphrase",
},
tos: {
required: " is Required",
minlength: " requires at least 6 characters",
},
},
onkeyup: true,
onblur: true
});
And, in the ideal, I'd love something like this:
messages: {
email: {
required: " is Required",
email: " is Improperly Formatted",
remote: " already exists",
remote: {
username: function() {
var emailcheck = $('#email').val();
return $('#username_availability_result').html(emailcheck + ' is already in our system. Please log in here.');
},
},
},
},
Thanks again, and in advance, for your own ongoing attention and advice,
Z
ORIGINAL QUESTION
I'm using jQuery Validate to run routine validation on a registration form. But one of the features I wanted to add to the form's functionality was an AJAX check to determine if an email address was already in the system. The problem is that the email check function exists outside of the validate function, and so doesn't actually stop the form from submitting when necessary.
Here's my code. (The top 50 lines comprise validation and password matching. The remainder constitutes the AJAX check [which is triggered by the email field's keyup event]).
// Method adds password matching abilities to the validator
jQuery.validator.addMethod("passmatch", function(value, element) {
return $('#password').val() == $('#password-check').val()
}, "* Passwords should match");
$(document).ready(function(){
$("#signup").validate({
errorElement: "span",
errorPlacement: function(error, element) {
error.appendTo(element.prev());
//element.prev().replaceWith(error);
},
rules: {
"email": {
required: true,
email:true,
},
"password": {
required: true,
minlength: 8,
},
"password-check": {
required: true,
minlength: 8,
passmatch: true,
},
"tos": {
required: true,
minlength: 6,
}
},
messages: {
email: {
required: " is Required",
email: " is Improperly Formatted",
},
password: {
required: " is Required",
minlength: " requires at least 8 characters",
},
"password-check": {
required: " is Required",
minlength: " requires at least 8 characters",
passmatch: " must match the Password"
},
tos: {
required: " is Required",
minlength: " requires at least 6 characters",
},
}
});
//check email availability
$('#email').keyup(function(){
check_availability();
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#email').val();
//use ajax to run the check
$.post("/ajax/emailcheck.php", { username: username },
function(result){
//if the result greater than none
if(result > 0 ){
//show that the username is not available
$('#username_availability_result').html(username + ' is already in our system. Please log in here.');
}else{
//username available.
//clear any messages
$('#username_availability_result').html('');
}
});
}
Is there a way for the check_availability() function to trigger a stop (and a start once it's cleared) so that the form can't be submitted during a state of error? Or can the whole kit and caboodle somehow be integrated into Validate using addMethod (if so, please note that I'm providing availability feedback in a specifically IDed element, not through the same element where other Validate errors appear)?
Thanks in advance for all your help and advice.
Z
Use the remote option of validation plugin that already has a built in ajax method that will bind to the input
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
Alternatively required can also be a function ( will not work on keyup or blur)
email:{ required: function(){
return $('#username_availability_result').html()=='';
}
}
Also, why not reset the email field if ajax returns a duplication? Your code would likely work as is with a reset of the field
Best suggestion is use built in remote
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#singupfrom").validate({
rules: {
'useremail': {// compound rule
required: true,
email: true,
remote:{
url: "check_email.php",
type: "post",
data:
{
emails: function()
{
return $('#singupfrom :input[name="useremail"]').val();
}
}
}
}
},
// here custom message for email already exists
messages: {
useremail: { remote: "Email already exists"}
}
});
});
</script>
<!-- your user email-->
<label>Email :</label>
<input type="text" name="useremail" id="useremail" value="" />
<!-- your user email end -->
// your php file "check_email.php" will be some thing like it
/// get or post can also be used in place of request depending on situation
$email = $_REQUEST['useremail'];
<?php
$check = "your query to check the email and returns the no of rows/ emails exists ";
if ($check == '0' or empty($check)) {
echo 'true';
} else {
echo 'false';
}
?>