i've a problem with Dropdown pop-up.
in my Dropdown there is option "Add New" when i click on "Add New" pop should open..which can not open now !
Here Is Dropdown's Code
echo form_dropdown('Birth_Certificate_Storage_id['.$key.']', $optionstorage,"",array('class'=>'form-control roleId','id'=>'Birth_Certificate_Storage_id['.$key.']','onchange'=>'addRole(this.options[this.selectedIndex].text)'));
i have put "onchange" event in dropdown and make function "addRole()"
addRole() Function
function addRole(val)
{
//alert("test");
if (val == "ADD NEW")
{
$('#RoleModal').modal('show');
$('#form_role').validate({
rules:
{
Storage Code: { required: true},
Storage Location: { required: true},
},
messages:
{
Storage Code: {required: "This field is Required"},
Storage Location: {required: "This field is Required"}
}
});
}
}
Function isn't working,i can not alert in that function
any help would be appreciated
updated:
The forth parameter of form_dropdown function should be a string not an array, like:
echo form_dropdown('Birth_Certificate_Storage_id[' . $key . ']', $optionstorage, "", 'class="form-control roleId" id="Birth_Certificate_Storage_id[' . $key . ']"');
If you use jQuery you can bind the change event in your javascript code/file instead of set it inline:
$(document).ready(function () {
$('.form-control.roleId').on('change', function () {
var val = $(this).find("option:selected").text();
if (val == "ADD NEW") {
$('#RoleModal').modal('show');
$('#form_role').validate({
rules : {
'Storage Code' : {required: true},
'Storage Location': {required: true}
},
messages: {
'Storage Code' : {required: "This field is Required"},
'Storage Location': {required: "This field is Required"}
}
});
}
});
});
Please notice I fixed some problems in your JS!
Related
Here is my html select box (options will come by ajax call) with multiselect function and validation
<select id="chapterId" name="chapter[]" class="multiselect-ui form-control" multiple="multiple"></select>
$('#chapterId').multiselect({
includeSelectAllOption: true
});
var $validator = $("#orderPaper").validate({
rules: {
'chapter[]': {required: true, min: 1},
},
messages: {
'chapter[]': {required: "Please select chapter"},
}
});
also multiselect.js is included properly.
its shows error every time 'Please select chapter' weather chapters selected or not.
I also checked that chapters are selected properly i can also get selected chapter ids.
but the jquery error is showing every time.
You just need to use custom validation rule. Try with this.
var $validator = $("#orderPaper").validate({
rules: {
'chapter[]': {required: true, needsSelection: true},
},
messages: {
'chapter[]': {required: "Please select chapter", needsSelection: "Please select chapter"},
}
});
$.validator.addMethod("needsSelection", function (value, element) {
var count = $(element).find('option:selected').length;
return count > 0;
});
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."
}
},
});
});
Hi I'm doing a validation form. I use codeigniter so I do of course a first validation with php.
I have a .js file to validate the form too. The thing is that some changes were made and now the file is no longer working properly.
When a field passes validation, a green icon appears next to the field. When it doesn't then the input box appears in red.
A field that is not working is documentn. I made a function to check if the document is already on the database. It worked on the past, now I can't figure out why is not working.
This is a snippet from the file:
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: "",
onfocusout: function (element) {
$(element).valid();
},
rules: {
documentn: {
required: true,
minlength: 7,
maxlength: 20,
digits: true,
remote: {
url: '/checkDocNumber',
type: 'POST',
data: {
documentn: function(){
var dn = $('#documentn').val();
$("#documentn").removeData("previousValue");
return dn;
}
}
}
},
this is snippet from my admin.php:
public function updateFrontUser(){
$result = array();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->database();
$this->form_validation->set_rules('documentn', 'Nro de Documento', 'required|min_length[7]|max_length[20]|is_natural');
this is function to check if document already exists on the database:
public function checkDocNumber(){
if (isset($_POST['documentn'])){
$dn = UserManager::getInstance()->getByDocument($_POST['documentn']);
if ($dn){
echo "true";
}else{
echo "false";
}
}
}
how can I check if data from remote rule is being passed to my checkDocNumber function?
EDIT
when I do a browser inspection no error appears!
Problem Solved. Just changed url from checkDocNumber to /admin/checkDocNumber
Still can't understand why it worked before with url being just checkDocNumber.
documentn: {
required: true,
minlength: 7,
maxlength: 20,
digits: true,
remote: {
url: '/admin/checkDocNumber',
type: 'POST',
data: {
documentn: function(){
var dn = $('#documentn').val();
$("#documentn").removeData("previousValue");
return dn;
}
}
}
},
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
}
}
});
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';
}
?>