jQuery Validate Plugin - How to create a simple custom rule? - javascript

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
}
});
}):
});

Related

Set regex for only 2 decimal numbers + dot + comma with jquery validator plugin

I use jQuery Validation Plugin to perform client side form validation. It works well. However, I don't know precisely Regex and I'm not able to achieve what I want.
I would like to add 3 different Regex in order to display 3 different messages depending on what the user enter in input field.:
Regex 1 detect if it is not a number with a specific message
Regex 2 accept dot or comma for decimal with a specific message
only 2 numbers for decimal after dot or comma with a specific message
There are plenty of questions related but I've tried a lot of answers on SO which don't work well.
Here is a working snippet
jQuery.validator.addMethod("decimal", function(value, element) {
// Validating Decimal Numbers
return this.optional(element) || /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g.test(value);
}, 'Please enter only numbers (format 0.00)');
jQuery.validator.addMethod("two_decimal", function(value, element) {
// require 2 decimals
return this.optional(element) || /^((\d+(\\.\d{0,2})?)|((\d*(\.\d{1,2}))))$/.test(value);
}, "Pleaser enter 2 numbers after dot");
// https://jqueryvalidation.org
$("#test_form").validate({
submitHandler: function(form) {
form.submit();
},
// rules, options, etc.,
onkeyup: function(element) {
// "eager" validation
this.element(element);
},
rules: {
decimal_number: {
required: true,
minlength: 1,
maxlength: 10,
decimal: true,
two_decimal: true
}
},
messages: {
montant_demande: {
required: "Please enter a number",
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.3/dist/jquery.validate.min.js"></script>
<form class="cmxform" id="test_form" method="get" action="">
<fieldset>
<legend>Test</legend>
<p>
<label for="decimal_number">Number decimal</label>
<input id="decimal_number" name="decimal_number" minlength="2" type="text" required>
</p>
</fieldset>
</form>
If you want only number , or decimal with coma , and dot . separator with only two decimals ,
See below snippet :
let decimalMessage = "";
jQuery.validator.addMethod("decimal", function(value, element) {
let decimal = /[^0-9.,]/g.test(value);
let decimalWithTwoDecimalNumber = /^\d+([.,]\d{2})?$/.test(value);
if(decimal) {
decimalMessage = 'Please enter only numbers (format 0.00)'
return this.optional(element);
}
if(decimalWithTwoDecimalNumber )
decimalMessage = 'Pleaser enter 2 numbers after dot'
return this.optional(element)||decimalWithTwoDecimalNumber
},function(params, element) {
return decimalMessage
});
// https://jqueryvalidation.org
$("#test_form").validate({
submitHandler: function(form) {
form.submit();
},
// rules, options, etc.,
onkeyup: function(element) {
// "eager" validation
this.element(element);
},
rules: {
decimal_number: {
required: true,
minlength: 1,
maxlength: 10,
decimal: true,
}
},
messages: {
montant_demande: {
required: "Please enter a number",
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.3/dist/jquery.validate.min.js"></script>
<form class="cmxform" id="test_form" method="get" action="">
<fieldset>
<legend>Test</legend>
<p>
<label for="decimal_number">Number decimal</label>
<input id="decimal_number" name="decimal_number" minlength="2" type="text" required>
</p>
</fieldset>
</form>

Error text is not being displayed for function result

I've successfully used the definition on other pages before. Basically it should make the field required, but fail if only whitespace is entered (by default typing i.e. a single space causes the required check to pass). I tossed an alert in just to see when the handler is fired as well as the value of this at that time. It's fired when I expect it, and the value is as I expect it. It should be returning false but apparently it isn't because the error isn't being displayed. If I remove that depends function and just have required: true, it correctly displays the error when the user leaves the field. What's going on?
ContactName: {
required: {
depends: function() {
alert("'" + $(this).val() + "'");
if ($.trim($(this).val()).length === 0) {
$(this).val($.trim($(this).val()));
return false;
}
return true;
}
},
maxlength: 100
}
You can change the rule for ContactName like (for details take a look to rules examples):
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
The snippet:
$("#commentForm").validate({
rules: {
ContactName: {
required: true,
minlength: {
depends: function(ele) {
if (ele.value.trim().length === 0) {
ele.value = '';
return false;
}
return true;
}
},
maxlength: 100
}
},
messages: {
ContactName: "Please enter your contact name"
}
});
<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.16.0/jquery.validate.min.js"></script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="ContactName">Name</label>
<input id="ContactName" name="ContactName" type="text">
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>

Validating field's with variable id. How to output errors. jQuery validation plugin

(1) I have next html:
<form method='post' action='' id='#countersForm'>
<label class='error' id='88'></label>
<input id="88" class="counter_input active" type="text" enabled="">
<label class='error' id='89'></label>
<input id="89" class="counter_input active" type="text" enabled="">
</form>
I need to validate this fields with jquery validation plugin.
How I can do this in case that fields are variables? For 1 user id will be 100 and 1000, for another 55 and 123. What jquery code I need to validate this.
if($("#countersForm").length)
{
$("#countersForm").validate({
rules: {
"89": {
required: true,
minlength: 2
}
},
messages: {
"89": {
required: "We need your email address to contact you",
minlength: jQuery.format("At least {0} characters required!")
}
}
});
}
(2) In what fields messages from 'messages' section will be printed? How I can specify them? I find many articles about this plugin at all, but there are not many (i still didn't find them) examples with output fields.
Maybe this code will help me:
$("#myForm").validate({
rules: {
field: {
required: true,
minlength: 10,
alphanumeric: true
}
},
messages: {
field: {
required: 'This is required.',
minlength: 'Please enter at least 10 characters.',
alphanumeric: 'No special characters.'
}
},
errorPlacement: function(error) {
$("#response").html(error);
}
});
But it place error in #responce element. I need to output error near input field. Can I somehow get id of current-validating-element and output error to label, connected to this element?
Try .insertafter()
errorPlacement: function(error, element) {
error.insertAfter(element);
}
ID must be unique use classes instead .
Two elements should not have same id.
Read Two HTML elements with same id attribute: How bad is it really?

jQuery - Validate Password

I am trying to use jQuery to validate my two password fields with each other.
My code looks like this:
jQuery('#settingsForm').validate(
rules : {
npassword : {
},
pass_check : {
equalTo : '#npassword'
}
}
});
This is the HTML for the input fields:
<label for='npassword'>New Password</label>
<input type='password' class='span10 password_check' name='npassword' id='npassword' value='' placeholder='New Password'>
<div class='separator'></div>
<label for='pass_check'>Confirm New Password</label>
<input type='password' class='span10' name='pass_check' id='pass_check' value='' placeholder='Confirm New Password'>
<div class='separator'></div>
Although this doesn't do anything. What should I change? I am new to jQuery and Javascript in general.
Thanks in advance.
You should fill out the configuration for npassword, e.g. by using required: true. See here: http://jsfiddle.net/JtTgM/
1) You are missing an opening brace, {, right after .validate(:
jQuery('#settingsForm').validate({ // <-- opening brace { was missing
2) Maybe you want to specify the required rule for the first password field. Otherwise, when both fields are blank, they both match and the form is valid.
npassword: {
required: true
},
3) You can override the default messages with the messages option:
jQuery('#settingsForm').validate({
rules: {
npassword: {
required: true
},
pass_check: {
equalTo: '#npassword'
}
},
messages: {
npassword: {
required: "this field is required"
},
pass_check: {
equalTo: "the passwords must match"
}
}
});
Working DEMO: http://jsfiddle.net/vsLWg/
$( "#Form").validate({
rules: {
old_password: "required",
password: "required",
new_password: {
equalTo: "#password"
}
}
});

Jquery Validation on cloned elements

I am using the following JQuery validation:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I have the following element:
<div class="form-item">
<label for="Reference_name" class="required">Name: <span class="required">*</span></label>
<input name="Reference[name][]" class="form-input validate {validate:{required:true,minLength:2,messages:{required:'Your name is required',minLength:'Your name is too short'}}}" id="Reference_name" type="text">
</div>
I have cloned the element but the validation is only appearing on the first element. I would like it to validate against the second too and show the error message label.
Can someone help with this please.
elements must be unique
<label for="Reference_name" class="required">Name:<span class="required">*</span></label>
<input type="text" id="Reference_name" name="Reference[Name]" id="Reference_name" required="required" maxlength="255" />
File Js
$(document).ready(function() {
validate_form();
});
function validate_form() {
$("#id_of_your_form").validate({
rules: {
'Reference_name': {
required:true,
minlength: 2,
}
},
},
messages: {
'Reference_name': {
required:"Your name is required",
minLength:'Your name is too short'
},
}
});
}
if you want to compare two fields
http://docs.jquery.com/Plugins/Validation/Methods/equalTo#other
Put your validation function in a global variable like this:
var validate_form_function = function(){
if($(".app-form").length > 0){
$('.app-form').validate({
rules: {
comment_message: {
required: true,
minlength: 2
}
},
messages: {
comment_message: {
required: "Your message",
minlength: "Your message"
}
}
});
}
};
Then revalidate your cloned form with the function like this :
validate_form_function();

Categories

Resources