I have small form :
Following is the script where I am validating the required field for input field which is working perfectly now I want to validate url using jquery.validate.min.js.
<script type="text/javascript" >
$(document).ready(function() {
var container = $('#error');
$("#rssform").validate({
errorContainer: container,
errorLabelContainer: $(container),
meta: "validate",
rules: {
feedurl: {
required:true
}
},
messages: {
feedurl: {
required:"Please Enter the URL"
}
}
});
});
</script>
<form action="rssindex.php" method="POST" id="rssform">
<label>Enter the feed URL </label>
<input type="submit" name="submit" value="GO" id="submit"/>
</form>
How can I do this. Any solution?
Thanks
jQuery validate plugin provide method to validate url.
Example:
$("#myform").validate({
rules: {
field: {
required: true,
url: true
}
}
});
For your code, add url: true to the rules.
feedurl: {
required:true,
url: true //here
}
Related
I've well researched and used this, but I don't know it is still getting error.
I need to check if existing image exists then file attribute should skip validation and viceversa.
HTML COde:
<input type="file" name="image" id="image">
<input type="hidden" name="old_image" value="">
JQuery Validation Code:
$("#add_reference").validate({
rules: {
link: {
required: true,
},
image:{
//required: true,
required: function(element) {
if ($("#old_image").val() == '')
{
return true;
}
else
{
return false;
}
},
accept:"jpg,png,jpeg,gif"
},
},
messages: {
link: {
required: "Please enter link title",
},
image:{
required: "Please choose image",
accept: "Please choose valid image files",
},
},
errorPlacement: function (error, element) {
var attr_name = element.attr('name');
error.insertAfter(element);
}
});
Can Anyone tell me where I am going wrong?
There is no id in your input tag,instead you should add id attribute.
<input type="hidden" name="old_image" id="old_image" value="">
and you are calling it by id
if ($("#old_image").val() == '')
<input type="file" name="image" id="image">
<input type="hidden" id="old_image" name="old_image" value="">
Your validation won't fire because it is always passing the test, you are testing if #old_image is empty and as you can see it is always empty, are you triggering an event after you upload your file???
You can do it with this event..
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$("#old_image").val(fileName);
});
});
I have a custom method
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Z\s]*$/i.test(value);
}, 'Your name may only contain letters');
Here I am trimming whitespace and replacing any repeating whitespaces with only one. I am then validating to make sure there are only letters and spaces.
Is it possible to make it so the trimmed value is submitted with the form instead of what the user entered?
Use the submitHandler and you can make any action before submiting the form ,(form.submit())
See beleow a working snippet
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Z\s]*$/i.test(value);
}, 'Your name may only contain letters');
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5,
lettersandspaces: true
},
"age": {
required: true,
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"age": {
required: "Please, enter your age",
}
},
submitHandler: function (form) { // for demo
var newName = $("#name").val().replace(/\s+/g, ' ').trim()
$("#name").val(newName);
$(form).valid();
alert("Name = '"+newName+"'");
// comment return and uncomment form.submit(
return false; //form.submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<label for="name">Name :</label>
<input type="text" name="name" id="name" /><br><br>
<label for="age">Age : </label>
<input type="age" name="age" id="age" /><br><br>
<button type="submit">Submit</button>
</form>
In validation form by jquery. If you want change value input name before validate. Let try:
$('#form').validate({
rules: {
'name': {
normalizer: function(){
return $('#name').val().(/\s+/g, ' ').trim();
}
}
}
})
How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?
For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?
You can create a simple rule by doing something like this:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
And then applying this like so:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
Just change the contents of the 'addMethod' to validate your checkboxes.
$(document).ready(function(){
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "http://"+location.host+"/checkUser.php",
data: "checkUsername="+value,
dataType:"html",
success: function(msg)
{
//If username exists, set response to true
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"Username is Already Taken"
);
$("#regFormPart1").validate({
username: {
required: true,
minlength: 8,
uniqueUserName: true
},
messages: {
username: {
required: "Username is required",
minlength: "Username must be at least 8 characters",
uniqueUserName: "This Username is taken already"
}
}
});
});
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
return jQuery.validator.methods['date'].call(
this,value,element
)||value==("0000/00/00");
}, "Please enter a valid date."
);
// connect it to a css class
jQuery.validator.addClassRules({
optdate : { optdate : true }
});
Custom Rule and data attribute
You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true";
So to check if at least one of a group of checkboxes is checked:
data-rule-oneormorechecked
<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" />
addMethod
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
And you can also override the message of a rule (ie: Atleast 1 must be selected) by using the syntax data-msg-rulename="my new message".
NOTE
If you use the data-rule-rulename method then you will need to make sure the rule name is all lowercase. This is because the jQuery validation function dataRules applies .toLowerCase() to compare and the HTML5 spec does not allow uppercase.
Working Example
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
$('.validate').validate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<form class="validate">
red<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" data-msg-oneormorechecked="Check one or more!" /><br/>
blue<input type="checkbox" name="colours[]" value="blue" /><br/>
green<input type="checkbox" name="colours[]" value="green" /><br/>
<input type="submit" value="submit"/>
</form>
Thanks, it worked!
Here's the final code:
$.validator.addMethod("greaterThanZero", function(value, element) {
var the_list_array = $("#some_form .super_item:checked");
return the_list_array.length > 0;
}, "* Please check at least one check box");
You can add a custom rule like this:
$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);
And add it as a rule like this:
PhoneToggle: {
booleanRequired: 'on'
}
For this case: user signup form, user must choose a username that is not taken.
This means we have to create a customized validation rule, which will send async http request with remote server.
create a input element in your html:
<input name="user_name" type="text" >
declare your form validation rules:
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
the remote code should be like:
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
Step 1 Included the cdn like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Step 2 Code Like
$(document).ready(function(){
$("#submit").click(function () {
$('#myform').validate({ // initialize the plugin
rules: {
id: {
required: true,
email: true
},
password: {
required: true,
minlength: 1
}
},
messages: {
id: {
required: "Enter Email Id"
},
password: {
required: "Enter Email Password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}):
});
Guys I am using jQuery Validation plugin to validate the Input Text fields...
like this:
$("#formSettings").validate({
rules: {
sta: {
required: true,
},
crs: {
equalTo: "#password"
}
},
messages: {
email: {
required: "Please Provide Your Email Address",
email: "Provide Valid Email Address"
},
});
The issue: I need to match one textfield value with the other, each textfield have comma separated values and they should match before continuing, any idea how can I do that
like if textfield 1 is: 1,2,3,4,5,6 then textfield2 should match.
$('#selector').val().length
Above the basic jQuery version of .length After that you could do an if statement. Here is a brief untested test you try:
<input type="text" value="1,2,3,4,5" id="thing1">
<input type="text" value="1,2,3,4" id="thing2">
<input type="button" name="submit" value="submit" id="submit">
$('#submit').click(function(event){
var thing1 = $('#thing1').val().length;
var thing2 = $('#thing2').val().length;
if (thing1 == thing2) {
return true;
} else {
alert("Contents must have same length");
return false;
}
});
And the fiddle: http://jsfiddle.net/8XQB3/
I am using jquery validate plugin to validate dynamically loaded form. For some cases I'm loading the content using $.post and in the callback I call a function that adds the validation rules. That works. For some content, I am using $.get and in that callback I am also calling a function that adds the validation rules. However, when using $.get the form is not validated at all.
What is my problem? Is there really any kind of difference using post and get in this perspective?
I think this is the significant code but I did add a lot of code after this in case it's needed. This is where I call the function that adds the validation rules:
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid }, function(data){
//Now, add the validation rules:
addUpdateAgentValidation();
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
$("#dialog-modal").html(data).dialog("open");
This is the code loading the form:
$("#agents td").live('click',function(event)
{
//alert("Agents");
event.preventDefault();
var col = $(this).parent().children().index($(this));
var $td= $(this).closest('tr').children('td');
var $agentid=$td.eq(2).text();
var $name=$td.eq(3).text();
if(col==0){
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid }, function(data){
//alert("GETDONE");
//Now, add the validation rules:
addUpdateAgentValidation();
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
$("#dialog-modal").html(data).dialog("open");
});
//and the rest of the code
//.
//.
Here is the function for adding the validation rules:
function addUpdateAgentValidation(){
//alert("GETDONE 2");
$("#updateagentform").validate({
errorContainer: "#updateagentmessagebox",
errorLabelContainer: "#updateagentmessagebox ul",
wrapper: "li", debug:true,
rules: {
email1: {// compound rule
// required: true,
email: true
},
email2: {
// required: true,
equalTo: "#email1"
},
username: {
// required: true,
remote: "http://localhost/SMICAdmin/smicsoap/soap_is_agentusername_available.php"
},
password: {
// required: true
},
password2: {
//required: true,
equalTo: "#password1"
}
},
messages: {
email1: {// compound rule
email: "Korrekt emailadress saknas"
},
email2: {
equalTo: "Mailadresserna matchar inte varandra"
},
//username: "Anv‰ndarnamnet mÂste vara unikt"
username: {
remote: "Användarnamn finns redan"
},
password2: {
equalTo: "Lösenord inte lika"
}
}
});
};
And this is where where I post the form:
$("#updateagentform").live("submit", function(e){
//Prevent the form from submitting normally
// alert("Trying to submit user update");
e.preventDefault();
$.post("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php",$(this).serialize(),function(msg){
//alert the response from the server
//alert(msg);
$("#dialog-modal").dialog("close");
});
$("#usertable").empty();
$('#usertable').load("http://localhost/SMICAdmin/adminactivities/admin_load_agents.php");
$("#modalarea").empty();
$('#modalarea').css("visibility","hidden");
});
And the code generating the form:
echo "<div class='errormessage' id='updateagentmessagebox'>
<ul></ul>
</div>
<form id='updateagentform' method='post'>
Ändra önskade fält<br/>
* Förnamn: <input type='text' name='firstname' /> <br/>
* Efternamn: <input type='text' name='surname' /> <br/>
* Email: <input id='email1' type='text' name='email1' /> <br/>
* Repetera email: <input id='email2' type='text' name='email2' /> <br/>
* Användarnamn: <input id='username_ID' type='text' name='username' /><br/>
* Lösenord: <input id='password1' type='text' name='password' /><br/>
* Repetera lösenord: <input id='password2' type='text' name='password2' /><br/>";
foreach ($roles as $key=>$role) {
if(in_array($key, $role_ids)){
echo "<input type='checkbox' name='rid".$key."' value='rid".$key."' checked />".$role."<br/>";
}else{
echo "<input type='checkbox' name='rid".$key."' value='rid".$key."' />".$role."<br/>";
}
}
echo "<input id='submitupdateagentform' type='submit' value='Uppdatera agent' /></form>";
What is my problem and how do I fix it?
You're calling .validate() on a form that doesn't exist on the page yet.
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid },
function(data){
// form does not exist in DOM here
addUpdateAgentValidation();
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
// form exists after this line.
$("#dialog-modal").html(data).dialog("open");
});
You need to rearrange your function call so that .validate() gets called after the form gets appended to the DOM:
$.get("http://localhost/SMICAdmin/adminactivities/admin_update_agent.php", { agent_id: $agentid },
function(data){
$('#dialog-modal').dialog( "option", "title", 'Uppdatera agent');
$("#dialog-modal").html(data).dialog("open");
addUpdateAgentValidation();
});