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';
}
?>
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."
}
},
});
});
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!!!
I am trying to validate my form using jQuery Validation plugin.
Here is the code
$(document).ready(function(){
var productsForm=$('#products-form');
productsForm.validate({
//debug:true,
invalidHandler: function(event, validator) {
// '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 span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
},
rules:{
productName: {
required: true,
minlength:2,
//here i tried to create a function
onfocusout: function(element){
var myValue=$(element).val();
if(myValue.match(/[<>$]/))
{
alert('Please enter the Name without any tags.');
$(element).valid=false;
}
}
},
productType: {
required: true,
minlength:2,
},
productBrand: {
required: true,
minlength:2,
},
description: {
required: true,
minlength:10,
maxlength:150,
},
updatedBy:{
required:true,
minlength:2,
}
},
messages:{
productName:{
required: "Please enter the productName",
minLength: "The name should be atleast 2 characters long",
},
productType: {
required: "Please enter the productType",
minlength:"The type should be atleast 2 characters long",
},
productBrand: {
required: "Please enter the productBrand",
minlength:"The Brand Name should be atleast 2 characters long",
},
description: {
required: "Please describe your product",
minlength: "The description should be atleast 10 characters long",
maxlength: "You can not enter more than 150 characters",
},
updatedBy:{
required: "PLease Your name",
minlength: "The name should be atleast 2 characters long",
}
},
submitHandler: function(form){
if(productsForm.valid())
{
alert('tada');
return false;
}
else
{
alert('not valid');
return false;
}
}
});
});
Now I am trying to create a function which checks whether the input values contain HTML tags or not. If yes then show the error msg and do not submit the form. But I do not know how to do that. Can anyone help please?
I tried to create a function as onfocusout but do not know how to add error.
Quote Title:
"how to check for HTML tags and then add error in jQuery Validation"
If you're using the jQuery Validate plugin, you only need to specify a rule for a field and the corresponding error message is toggled automatically. There are built-in methods for creating custom rules and built-in methods for over-riding any error text with your custom text. The plugin automatically blocks the form submission during any error including errors triggered from your custom rules.
Quote OP:
"Now I am trying to create a function which checks whether the input
values contain html tags or not. If yes then show the error msg and
do not submit the form."
Your second sentence merely describes what every single validation rule does. Checks the input data and blocks submission on failure of this test. Your first sentence is what you want your rule to do... make sure the input contains no tags.
Quote OP:
"I tried to create a function as onfocusout but do not know how to add error."
Your code attempt indicates that you're making this way way more complicated than it needs to be. You do not need to tinker with any single callback function of the plugin just to create one new rule... at that point you might as well write your own validation plugin from scratch.
To achieve what you want, you simply need to use the addMethod method to write your own custom jQuery Validation rule. In this case, you'll need a regex that will exclude HTML tags... perhaps by only allowing letters and numbers. (Tweak the regex or replace the function with anything you see fit).
Refer to this really basic example:
jQuery.validator.addMethod("noHTML", function(value, element) {
// return true - means the field passed validation
// return false - means the field failed validation and it triggers the error
return this.optional(element) || /^([a-z0-9]+)$/.test(value);
}, "No HTML tags are allowed!");
$('#myform').validate({
rules: {
field1: {
required: true,
noHTML: true
}
}
});
DEMO: http://jsfiddle.net/mM2JF/
However, the additional-methods.js file already includes various rules that would automatically exclude any HTML...
letterswithbasicpunc => "Letters or punctuation only please"
alphanumeric => "Letters, numbers, and underscores only please"
lettersonly => "Letters only please"
$('#myform').validate({
rules: {
field1: {
required: true,
alphanumeric: true // <- will also not allow HTML
}
}
});
DEMO 2: http://jsfiddle.net/mM2JF/1/
Try this Code to Validate the HTML tags
jQuery.validator.addMethod("noHTMLtags", function(value, element){
if(this.optional(element) || /<\/?[^>]+(>|$)/g.test(value)){
return false;
} else {
return true;
}
}, "HTML tags are Not allowed.");
$('#form').validate({
rules: {
message: {
required: true , noHTMLtags: true
}
}});
I Hope this is also a good example.
Here is the exmple of what i hve done
$.validator.addMethod("CHECKDOB", function(value, element) {
return this.optional(element) || check_blank_dob(element);
}, "Please Enter Birth Date");
//See checkdob function is added to validator
Now
In rules
rules:{
<%=txtfirstname.UniqueID %>: {required: true}, <%=txtlastname.UniqueID %>: {required: true},
<%=txtdateofbirth.UniqueID %>: { required: true,
CHECKDOB:"Please Enter Birth Date",//see here i have called that function
date:true
},
now messages
messages: {
<%=txtfirstname.UniqueID %>:{required: "Please Enter First Name"},
<%=txtlastname.UniqueID %>:{required: "Please Enter Last Name"},
<%=txtdateofbirth.UniqueID %>:{
required: "Please Enter Birth Date",
CHECKDOB:"Please Enter Birth Date",
date:"Invalid Date! Please try again"
},
Here is your function
function check_blank_dob()
{
var birth=document.getElementById("<%=txtdateofbirth.ClientID%>").value
if(birth=="__/__/____")
{
return false;
}
return true;
}
See this function i have called at checkdob function when adding method to validator
This is just the example how to add you have to implement your method i hope this will help you regards....:)
I use regular expression for preventing HTML tags in my textarea
$.validator.addMethod(
"no_html",
function(value, element) {
if(/<(.|\n)*?>/g.test( value )){
return false;
}else{
return true;
}
},
"HTML tag is not allow."
);
$('#myform').validate({
rules: {
field1: {
required: true,
no_html: true
}
}
});