I have a simple form written in AngularJS.
I would like to make the form invalid immediately after loading. Unfortunately $scope.myForm.$valid = false; doesn't want work. Do you have any other technique to do it? It is important for me as I want to let user click the button only when he/she choose at least on checkbox. Now you can submit the form always after loading the form.
<form name="myForm" ng-submit="myForm.$valid">
<input type="checkbox" ng-model="obj.first" ng-change="onChange()" /> First <br />
<input type="checkbox" ng-model="obj.second" ng-change="onChange()"/>Second <br />
<input type="checkbox" ng-model="obj.third" ng-change="onChange()"/> Third <br>
<button type="submit" ng-disabled="!myForm.$valid" ng-click="click()">test</button> <br>
</form>
$scope.myForm = {};
$scope.myForm.$valid = false;
$scope.click=function () {
console.log('-------------2', $scope.myForm);
};
$scope.onChange=function () {
console.log('before:', $scope.myForm);
var isValid = false;
angular.forEach($scope.obj, function(value, key) {
if(value == true){
isValid=true;
}
console.log(key + ': ' + value);
});
if(!isValid){
$scope.myForm.$valid = false;
$scope.myForm.$error.checkBoxes = {
isChecked: false
};
}
console.log('after:', $scope.myForm);
}
So this is my final solution, the form in the scope has a function called $setValidity() where we can change the validity state, and notify the form. Refer here, so I check if any of the checkboxes are having true value, then I set the value for one checkbox alone as true, if not then one of the checkboxes with name one is set to $valid = false, thus the entire form will be invalid, please go through my code for the implementation of the solution!
JSFiddle Demo
JS:
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.onChange = function() {
if ($scope.obj) {
if ($scope.obj.first || $scope.obj.second || $scope.obj.third) {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", true);
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
} else {
$scope.myForm.one.$setValidity("Atleast one checkbox needs to be selected", false);
}
}
});
Try this in your submit button. hope it works
data-ng-disabled="myForm.$submitted || myForm.$invalid && !myForm.$pristine"
I am using https://jqueryvalidation.org/ to validate my form on the frontend. The basic "if field is empty - validate" works OK.
But I'd like to the submit button to be initially disabled until a valid email address has been entered. I'd like the button to become enabled as soon as the field becomes valid (on keypress).
So basically I just need to remove the 'btn-disabled' class once its valid.
I'm struggling with the jQuery to add this function/method. Would be grateful if someone can help out.
Heres a slightly simplifed version: http://codepen.io/dagford/pen/kXJpEZ
$(document).ready(function(){
$("#reset-form").validate({
rules: {
emailaddress: {
required: true,
email: true
}
},
messages: {
email: "Please enter a valid email address"
}
});
});
you can check if the form is valid after entering the email address. Keep you button disabled by default and remove the disabled attribute once you validate the form.
$("#emailaddress").on("blur", function(){
if($("#reset-form").valid())
{
$("#btn-reset").removeAttr("disabled");
}
});
Code Pen : http://codepen.io/anon/pen/YWLjKX?editors=1010
You have attr for this
$('#button1, #button2').attr("disabled", true);
Check this :
<script type="text/javascript">
(function() {
$('form > input').keyup(function() {
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') { // write your code for valid email here
empty = true;
}
});
if (empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>
I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?
The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value
Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .
function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});
How do I empty a textfield (html form) if I click in it to write something.
Pseudo Code:
On click #searchform
Erase String in #searchform
$('#searchform').click(function() { $(this).val('') })
Try it here
$('#searchform').click(function() {
if ($(this).val() == 'Enter search term') {
$(this).data('original', $(this).val()).val('');
}
});
$('#searchform').blur(function() {
if ($(this).val() == '') {
$(this).val($(this).data('original'));
}
});
EDIT As of now you should use the placeholder attribute and if you want, use the above as a polyfill for missing placeholder support.
if (!('placeholder' in document.createElement('input'))){
$('input[placeholder]').each(function() {
$(this).placeholder();
});
}
And turn the original code into a plugin for easy use (with some small mods).
jQuery.fn.placeholder = function() {
return this.each(function() {
var value = $(this).attr('placeholder');
jQuery(this).val(value).addClass('placeholder');
jQuery(this).focus(function() {
if (jQuery(this).val() == value) {
jQuery(this).val('').removeClass('placeholder');
}
});
jQuery(this).blur(function() {
if (jQuery(this).val() == '') {
jQuery(this).val(value).addClass('placeholder');
}
});
});
};
I'd recommend you using the HTML5 placeholder attribute. For example:
<input type="text" placeholder="some default string if empty" />
This will work with most of the newest browsers and for older ones there is a workaround jQuery plugin. Here is the link to the placeholder plugin.
And then you simply call:
$('input[placeholder]').placeholder();
If you are wanting to clear a default value from a field such as "Enter Search Term" I use the following code:
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
and then on my input field I add:
onfocus="clearText(this)"
So it would be:
<input type="text" name="username" value="enter your name here" onfocus="clearText(this)">
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,
});
});