Using jquery validate with multiple fields of the same name - javascript

I am trying to get jquery validate to work on multiple fields. Reason being I have dynamically generated fields added and they are simply a list of phone numbers from none to as many as required. A button adds another number.
So I thought I'd put together a basic example and followed the concept from the accepted answer in the following link:
Using JQuery Validate Plugin to validate multiple form fields with identical names
However, it's not doing anything useful. Why is it not working?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$("#submit").click(function(){
$("field").each(function(){
$(this).rules("add", {
required: true,
email: true,
messages: {
required: "Specify a valid email"
}
});
})
});
$(document).ready(function(){
$("#myform").validate();
});
</script>
</head>
<body>
<form id="myform">
<label for="field">Required, email: </label>
<input class="left" id="field" name="field" />
<input class="left" id="field" name="field" />
<input class="left" id="field" name="field" />
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" id="submit" name="submit" />
</form>
</body>
</html>

This: $("field").each(function(){
Should be: $("[name=field]").each(function(){
Also your IDs should be unique, you'll get unpredictable behavior when this isn't true. Also, you should move the rule adding inside the document.ready, like this (this is now all your script):
$(function(){
$("#myform").validate();
$("[name=field]").each(function(){
$(this).rules("add", {
required: true,
email: true,
messages: {
required: "Specify a valid email"
}
});
});
});

#pratik
JqueryValidation maintaining rulesCache, You need to modify core library.
elements: function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled]")
.not(this.settings.ignore)
.filter(function() {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
rulesCache[this.name] = true;
return true;
});
},
Just comment the rulesCache[this.name] = true;
elements: function() {
var validator = this,
rulesCache = {};
// select all valid inputs inside the form (no submit or reset buttons)
return $(this.currentForm)
.find("input, select, textarea")
.not(":submit, :reset, :image, [disabled]")
.not(this.settings.ignore)
.filter(function() {
if (!this.name && validator.settings.debug && window.console) {
console.error("%o has no name assigned", this);
}
// select only the first element for each name, and only those with rules specified
if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
return false;
}
// rulesCache[this.name] = true;
return true;
});
},
If you don't want to change in core library file. there is another solution. Just override existing core function.
$.validator.prototype.checkForm = function (){
this.prepareForm();
for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
}
else {
this.check( elements[i] );
}
}
return this.valid();
};

Related

How trigger validation on a textbox when a button is pressed?

I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.

Handling form submission with Javascript - How to give user another chance?

My current application prevents blank and empty input from being submitted on the first attempt. If the initial input is valid, the search is executed. If it is invalid, the form becomes "unresponsive" and no other attempts can be made. How can I modify my code, ideally using plain JavaScript, to allow multiple attempts without reloading the page?
// welcome.js
function prepareEventHandlers() {
document.getElementById("new_search").onsubmit = validateForm
}
function validateForm() {
var q = document.getElementById("search_q").value;
var trimmed_q = q.trim();
if (trimmed_q.length < 1) {
return false;
} else {
return true;
}
}
window.onload = function() {
prepareEventHandlers();
}
// segment from home.html.erb
<%= form_for :search, url: {action: "results"}, html: {id: "new_search", method: "get"} do |f| %>
<%= f.text_field :q, placeholder: "Where to?", html: {id: "search_q"} %>
<%= f.submit "Search" %>
<% end %>
// rails generated html for home.html.erb -- omitted 30 lines of scripts from head
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<script src="welcome.js" type="text/javascript" charset="utf-8">
</script>
</head>
</head>
<body>
<div class="homeheader">
</div>
<div class="searchbar">
<h3 class="col-md-2"></h3>
<h3 class="col-md-10">
<form id="new_search" action="/results" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" />
<input placeholder="Where to?" html="{:id=>"search_q"}" type="text" name="search[q]" id="search_q" />
<input type="submit" name="commit" value="Search" data-disable-with="Search" />
</form></h3>
</div>
</div>
</body>
</html>
</body>
</html>
function validateForm(f) {
var ele = document.forms[f].elements;
var allValid = true;
for (var i in ele) {
if (!isChar(ele[i]) && ele[i].type!="radio" && ele[i].type!="checkbox") {
allValid = false;
ele[i].style.borderColor = "red";
}
}
if (!allValid) {
f.reset()
}
}
This code will check each field of your form to make sure there is at least 1 character in each element, as long as it's not a checkbox or radio button. Feel free to mix and match that if statement however you see fit. In the loop, if any of the fields are not valid, it sets the allValid flag to false and upon exiting the loop and evaluating that flag for false, it resets your form. Hope this helps!
I found the problem to be that on submit, the input of type submit was given the disabled option and this what not reset after validating the data. My code is still a work in process, but here is my not yet DRY solution:
// welcome.js
function prepareEventHandler() {
document.getElementById("new_search").onsubmit = validateForm
}
function validateForm() {
var q = document.getElementById("search_q").value;
var trimmed_q = q.trim();
if (trimmed_q.length < 1) {
return false;
} else {
return true;
}
}
window.onload = function() {
prepareEventHandler();
}
// (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){
document.getElementsByName("commit")[0].setAttribute("disabled", "true");
document.getElementById("search_q").onkeyup = function() {
var val = document.getElementById("search_q").value;
var trimmed_q = val.trim();
if(trimmed_q != '') {
document.getElementsByName("commit")[0].removeAttribute("disabled");
}
};
}, false);

How can I change maxlength parameter to validate a textarea considering only the letters and not the spaces?

I'm using jQuery validate a form and I need to display a textarea with minlength 1 letter and maxlength 500 letters.
How can I change maxlength parameter to validate a textarea considering only the letters and not the spaces?
Thanks
You need to create your own custom rule, see e.g:
$.validator.addMethod('customLength', function (value, elm, param) {
//Your Validation rule here
return elm.value.replace(/ /g,'').length <= 500; // return bool
});
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
customLength: true
}
},
messages: {
"name": {
required: "Please, enter a name",
customLength: 'Custom error message!'
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
Try this:
$(document).on('keyup','textarea',function(){
if($(this).val() != ""){
var textarea = $(this).val().replace(/ /g,'');
var length = textarea.length;
if(length > 500){
alert('Limit reached');
}
}
});
$(document).on('keyup','textarea',function(){
var textarea = $(this).val().replace(/ /g,'');
var newLength = textarea.length;
//set to new max length (basically 500 + whitespaces' length)
$(this).attr('maxlength',500 +($(this).val().length - newLength) );
});
If you are using jquery-validate that you mention. Then please add another js that is additional-methods.min.js which have a extra capability to handle custom logic
HTML page
<html>
<head>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jquery-validate.js"></script>
<script type="text/javascript" src="/js/additional-methods.min.js"></script>
</head>
<body>
<form id="formID" name="formID" method="post">
<textarea id="textareaID" name="textareaID" ></textarea>
<input id="submitBtn" type="submit">
</form>
<script>
$(document).ready(function(){
$("#formID").validate({
rules: {
textareaID:{
required:true,
checkLenght:true
}
},
messages: {
textareaID:{
required:'Please enter',
checkLenght:'msg..'
}
}
});
});
$.validator.addMethod("checkLenght", function(value, element){
var count = (value.match(/\d/g) || []).length;
if(count == 0 || count >500)
return false;
else
return true;
/*here is example regex you can write as per you requirement*/
});
</script>
</body>
</html>
For your further refrence : https://jqueryvalidation.org/jQuery.validator.addMethod/
Hope my explanation is works for you.

Disable form submit button input=text and input=checkbox with jquery

I have a form with three inputs ([type=text], multiple input[type=checkbox] and a disabled submit button).
I want the submit button to be enabled if a user has filled in all three text-inputs and has selected at least one of the checkboxes.
I found this fiddle which works great on all three text-inputs, but I'd like to add the additional condition that at least one checkbox must be selected:
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=password]');
function checkEmpty() {
// filter over the empty inputs
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur(); // trigger an initial blur
});
fiddle
Add class="checkbox" in the checkboxes then modify checkEmpty() to this:
function checkEmpty() {
var text= $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
var checkbox = false;
if ($(".checkbox:checked").length > 0) {
checkbox = true;
}
if(text == true && checkbox == true){
return true;
}else{
return false;
}
}
Then add the event on click for the checkboxes which is:
$(".checkbox").on("click", function(){
$submit.prop("disabled", !checkEmpty());
});
Hey just add input[type=checkbox] only in jquery part, here is your desired output, try below code:
Index.html
<form method="POST" action="">
User Name: <input name="Username" type="text" size="14" maxlength="14" /><br />
hobbies:<input type="checkbox" name="cricket">Cricket<input type="checkbox" name="football">football<input type="checkbox" name="hockey">hockey<br>
<input type="submit" value="Login" name="Submit" id="loggy">
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
var $submit = $("input[type=submit]"),
$inputs = $('input[type=text], input[type=checkbox]');
function checkEmpty() {
return $inputs.filter(function() {
return !$.trim(this.value);
}).length === 0;
}
$inputs.on('blur', function() {
$submit.prop("disabled", !checkEmpty());
}).blur();
});
</script>
Ok i have a serious problem now.
I'm using wordpress and added:
<?php wp_head(); ?>
<?php wp_footer(); ?>
To my header.php and footer.php, cause i need them so a plugin is getting loaded.
Since i added them the working solution from Stephan Sutter isn't working anymore. The submit button is still disabled if i fill in all required forms. If i remove them it works again, but i need them for the plugin.
I think it is because the plugin adds input text to the page. Is there any way i can use the code frm Stephan for a defined form ID=#addmovie-form?

jQuery Validation using the class instead of the name value

I'd like to validate a form using the jquery validate plugin, but I'm unable to use the 'name' value within the html - as this is a field also used by the server app.
Specifically, I need to limit the number of checkboxes checked from a group. (Maximum of 3.) All of the examples I have seen, use the name attribute of each element. What I'd like to do is use the class instead, and then declare a rule for that.
html
This works:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="salutation" value="1" />
This doesn't work, but is what I'm aiming for:
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" />
javascript:
var validator = $(".formToValidate").validate({
rules:{
"salutation":{
required:true,
},
"checkBox":{
required:true,
minlength:3 }
}
});
Is it possible to do this - is there a way of targeting the class instead of the name within the rules options? Or do I have to add a custom method?
Cheers,
Matt
You can add the rules based on that selector using .rules("add", options), just remove any rules you want class based out of your validate options, and after calling $(".formToValidate").validate({... });, do this:
$(".checkBox").rules("add", {
required:true,
minlength:3
});
Another way you can do it, is using addClassRules.
It's specific for classes, while the option using selector and .rules is more a generic way.
Before calling
$(form).validate()
Use like this:
jQuery.validator.addClassRules('myClassName', {
required: true /*,
other rules */
});
Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules
I prefer this syntax for a case like this.
I know this is an old question. But I too needed the same one recently, and I got this question from stackoverflow + another answer from this blog. The answer which was in the blog was more straight forward as it focuses specially for this kind of a validation. Here is how to do it.
$.validator.addClassRules("price", {
required: true,
minlength: 2
});
This method does not require you to have validate method above this call.
Hope this will help someone in the future too. Source here.
Here's the solution using jQuery:
$().ready(function () {
$(".formToValidate").validate();
$(".checkBox").each(function (item) {
$(this).rules("add", {
required: true,
minlength:3
});
});
});
Here's my solution (requires no jQuery... just JavaScript):
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 4)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
Put this in a script block at the end of <body> and the snippet will do its magic, limiting the number of checkboxes checked in maximum to three (or whatever number you specify).
Here, I'll even give you a test page (paste it into a file and try it):
<!DOCTYPE html><html><body>
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<input type="checkbox" class="salutation">
<script>
function argsToArray(args) {
var r = []; for (var i = 0; i < args.length; i++)
r.push(args[i]);
return r;
}
function bind() {
var initArgs = argsToArray(arguments);
var fx = initArgs.shift();
var tObj = initArgs.shift();
var args = initArgs;
return function() {
return fx.apply(tObj, args.concat(argsToArray(arguments)));
};
}
var salutation = argsToArray(document.getElementsByClassName('salutation'));
salutation.forEach(function(checkbox) {
checkbox.addEventListener('change', bind(function(checkbox, salutation) {
var numChecked = salutation.filter(function(checkbox) { return checkbox.checked; }).length;
if (numChecked >= 3)
checkbox.checked = false;
}, null, checkbox, salutation), false);
});
</script></body></html>
Since for me, some elements are created on page load, and some are dynamically added by the user; I used this to make sure everything stayed DRY.
On submit, find everything with class x, remove class x, add rule x.
$('#form').on('submit', function(e) {
$('.alphanumeric_dash').each(function() {
var $this = $(this);
$this.removeClass('alphanumeric_dash');
$(this).rules('add', {
alphanumeric_dash: true
});
});
});
If you want add Custom method you can do it
(in this case, at least one checkbox selected)
<input class="checkBox" type="checkbox" id="i0000zxthy" name="i0000zxthy" value="1" onclick="test($(this))"/>
in Javascript
var tags = 0;
$(document).ready(function() {
$.validator.addMethod('arrayminimo', function(value) {
return tags > 0
}, 'Selezionare almeno un Opzione');
$.validator.addClassRules('check_secondario', {
arrayminimo: true,
});
validaFormRichiesta();
});
function validaFormRichiesta() {
$("#form").validate({
......
});
}
function test(n) {
if (n.prop("checked")) {
tags++;
} else {
tags--;
}
}
If you need to set up multpile class rules you can do it like this:
jQuery.validator.addClassRules({
name: {
required: true,
minlength: 2
},
zip: {
required: true,
digits: true,
minlength: 5,
maxlength: 5
}
});
source: https://jqueryvalidation.org/jQuery.validator.addClassRules/
Disclaimer: Yes, I know it's 2021 and you shouldn't be using jQuery but, sometimes we have to. This information was really useful to me, so I hope to help some eventual random stranger who has to maintain some legacy system somewhere.
$(".ClassName").each(function (item) {
$(this).rules("add", {
required: true,
});
});

Categories