Multiple CheckBox Validation using spring JS? - validation

I am creating dynamic Check Boxes in runtime. my requirement is have to validate atleast one checkbox checked or not. am doing this using springJS. But to validate i have to pass checkBox Id to spring Validation, But this ID array creating in runtime. how can i achieve this? i tried all solutions but it did'nt worked for me. i am doing like this it was working if i hardcode checkbox id.
<script type="text/javascript">
Spring.addDecoration(
new Spring.ElementDecoration({
elementId: '_CheckBox_ids',
widgetType: 'dijit.form.CheckBox',
widgetModule: 'dijit.form.CheckBox',
validate: function () {
if (dojo.query("#roo_apiUser_profile > input[type=checkbox]", 'dijit.form').filter(function (n) {
return n.checked;
}).length > 0) {
return true;
} else {
alert('choose at least one profile');
return false;
}
},
widgetAttrs: {
required: true
}
}));
</script>

You may add the onsubmit attribute in your form tag and call a function that does the validation on checkboxes.
Alternately, you may create your own extension of AbstractElementDecoration (defined in spring.js) using dojo.declare and pass to the validate attribute a function that will do the checkboxes validation for you. For elementId you may pass in the id of a div element that contains all the checkboxes. Spring.ValidateAllDecoration calls Spring.validateAll function. Make sure you do the necessary tweaking in your AbstractElementDecoration extension so that there is no exceptions in Spring.validateAll.

Related

Laravel Livewire javascript code after model is load

I have one Laravel Livewire model open as bellow code
public function confirmItemAdd()
{
$this->resetValidation();
$this->confirmingItemAdd = true;
}
and my model window code in blade is
<x-jet-dialog-modal wire:model="confirmingItemAdd">
I have one select2 in model and want to set value of select2 on variable name $s2v
After search I findout that
$('.select2').val(s2v).trigger('change');
how can I set value of select2 on load on model?
Thanks
You can trigger a browser event from the livewire component and listen for that event and change the select2 value accordingly (assuming the select2 part is wire:ignored).
public $s2v = 'Test value';
public function confirmItemAdd()
{
$this->resetValidation();
$this->confirmingItemAdd = true;
$this->dispatchBrowserEvent('change-select2', $this->s2v);
}
in your layout file or with the stack in layout file you can listen for this event and trigger the change for the select2 as below,
<script>
$(window).on('change-select2', (e) => {
$('.select2').val(e.detail).trigger('change');
});
</script>
Note e.detail is the $s2v value passed from the livewire component.
And what validation error is giving to you? you are reseting the validation error before the dispatchBrowserEvent...seem that even by JS you are changing the select2 value the property doesn't
EDITED
Ok, first a have a particular issue with select2 rendering after each refresh and find this solution. In the component a have this:
public function hydrate()
{
$this->emit('select2');
}
and in blade parent or script section
<script>
$(document).ready(function() {
window.initSelectCompanyDrop=()=>{
$('#selectCompany').select2({
placeholder: '{{ __('locale.Select a Company') }}',
allowClear: true});
}
initSelectCompanyDrop();
$('#selectCompany').on('change', function (e) {
livewire.emit('selectedCompanyItem', e.target.value)
});
window.livewire.on('select2',()=>{
initSelectCompanyDrop();
});
});
</script>
If your issue with error bag persist, so you have to look into the kind of validation you're doing. In other case, I define global $message for a validation message but only works for $this->validate. Once I need redefine the validation, using Validator::make I have to create a new var $message for that inside the method

AngularJS: Is there any way to determine which fields are making a form invalid?

I have the following code in an AngularJS application, inside of a controller,
which is called from an ng-submit function, which belongs to a form with name profileForm:
$scope.updateProfile = function() {
if($scope.profileForm.$invalid) {
//error handling..
}
//etc.
};
Inside of this function, is there any way to figure out which fields are causing the entire form to be called invalid?
Each input name's validation information is exposed as property in form's name in scope.
HTML
<form name="someForm" action="/">
<input name="username" required />
<input name="password" type="password" required />
</form>
JS
$scope.someForm.username.$valid
// > false
$scope.someForm.password.$error
// > { required: true }
The exposed properties are $pristine, $dirty, $valid, $invalid, $error.
If you want to iterate over the errors for some reason:
$scope.someForm.$error
// > { required: [{$name: "username", $error: true /*...*/},
// {$name: "password", /*..*/}] }
Each rule in error will be exposed in $error.
Here is a plunkr to play with http://plnkr.co/edit/zCircDauLfeMcMUSnYaO?p=preview
For checking which field of form is invalid
console.log($scope.FORM_NAME.$error.required);
this will output the array of invalid fields of the form
If you want to see which fields are messing up with your validation and you have jQuery to help you, just search for the "ng-invalid" class on the javascript console.
$('.ng-invalid');
It will list all DOM elements which failed validation for any reason.
You can loop through form.$error.pattern.
$scope.updateProfile = function() {
var error = $scope.profileForm.$error;
angular.forEach(error.pattern, function(field){
if(field.$invalid){
var fieldName = field.$name;
....
}
});
}
I wanted to display all the errors in the disabled Save button tooltip, so the user will know why is disable instead of scrolling up and down the long form.
Note: remember to add name property to the fields in your form
if (frm) {
disable = frm.$invalid;
if (frm.$invalid && frm.$error && frm.$error.required) {
frm.$error.required.forEach(function (error) {
disableArray.push(error.$name + ' is required');
});
}
}
if (disableArray.length > 0) {
vm.disableMessage = disableArray.toString();
}
For my application i display error like this:
<ul ng-repeat="errs in myForm.$error">
<li ng-repeat="err in errs">{{err.$name}}</li></ul>
if you want to see everything, just user 'err' that will display something like this:
"$validators": {},
"$asyncValidators": {},
"$parsers": [],
"$formatters": [],
"$viewChangeListeners": [],
"$untouched": true,
"$touched": false,
"$pristine": true,
"$dirty": false,
"$valid": false,
"$invalid": true,
"$error": { "required": true },
"$name": "errorfieldName",
"$options": {}
Not this well formatted, but you will see these things there...
When any field is invalid, if you try to get its value, it will be undefined.
Lets say you have a text input attached to $scope.mynum that is valid only when you type numbers, and you have typed ABC on it.
If you try to get the value of $scope.mynum, it would be undefined; it wouldn't return the ABC.
(Probably you know all this, but anyway)
So, I would use an array that have all the elements that need validation that I have added to the scope and use a filter (with underscore.js for example) to check which ones return as typeof undefined.
And those would be the fields causing the invalid state.
If you want to find field(s) which invalidates form on UI without programmatically, just right click inspect (open developer tools in elements view) then search for ng-invalid with ctrl+f inside this tab. Then for each field you find ng-invalid class for, you can check if field is not given any value while it is required, or other rules it may violate (invalid email format, out of range / max / min definition, etc.). This is the easiest way.

MVC Custom Client side validation

In my mvc 3 application, I would like to execute a function when the user tries to submit the form. Within that function I will check a number of fields to determine if the user has provided the necessary data before submission.
How can I hookup a script to be executed when the user tries to submit the form?
(within the custom validate function, I need to check if various checkboxes have been selected and if yes, then additional values are selected from dropdownlists etc.)
How can I hookup a script to be executed when the user tries to submit the form?
You could subscribe to the .submit event of the form and after calling the standard client side validation call your custom function:
$(function() {
$('form').submit(function() {
if (!$(this).valid()) {
// standard client validation failed => prevent submission
return false;
}
// at this stage client validation has passed. Here you could call your
// function and return true/false depending on the result of your
// custom function
});
});
Another possibility is to write custom validation attributes and hook up a custom adapter as shown in this answer and a similar one.
$('#formId').submit(function () {
var standardIsValid = $(this).validate().form();
var customIsValid = customValidations();
if (!standardIsValid || !customIsValid) {
return false;
}
});
In the view (RAZOR or ASPX), you will define a script like you would in html, and in there will be your client-side validation.
For example :
<script>
//define your script here, ie. $.(#tagtovaildate).validate();
</script>
<html>
//code
</html>

MVC Form Validation

I am having trouble with my form validation. I have a form class with the Required attribute on it and I have ClientValidationEnabled to true in my web.config. I also have this call on my page #{Html.EnableClientValidation();}
I am using ajax form with the before submit option to catch the validation. Here is what I have:
$(document).ready(function () {
var options = {
beforeSubmit: ensureValid
};
$('#applyForm').ajaxForm(options);
});
function ensureValid(formData, jqForm, options) {
var result = $('#applyForm').validate();
console.log(result.valid());
return result.valid();
}
The code hits the ensureValid function but keeps continuing to the action in the controller even when I know a property should fire.
Thank you for any insight,
Brenna
If you are using asp.net-mvc-3, I would recommend at looking at using jquery.validate to perform your validation. It's far easier to setup, and generates cleaner code. You can see how to set this up in my blog post (I also cover a possible problem you could run into).

asp.net mvc 3 validation summary not showing via unobtrusive validation

I'm having problems getting the asp.net MVC client-side validation to work how I want it.
I have it basically working, however, the validation summary is not displayed until the user clicks the submit button, even though the individual inputs are being highlighted as invalid as the user tabs/clicks etc their way through the form. This is all happening client-side.
I would have thought the that the validation summary would be displayed as soon as an input field was discovered that was invalid.
Is this behaviour by design? Is there any way around it, as I would like the validation summary to be displayed as soon as it is discovered that one of the input fields is invalid.
My code is basically,
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
...
#using (Html.BeginForm())
{
#Html.ValidationSummary(false)
#Html.EditorFor(model => model);
...
And my _Layout.cshtml references jquery-1.4.4.min.js.
I used a version of Torbjörn Nomells answer
Except here I hang resetSummary off the validator object
$.validator.prototype.resetSummary= function () {
var form = $(this.currentForm);
form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul")
.empty();
return this;
};
Then change calling it to
$.validator.setDefaults({
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();
this.checkForm();
if (this.errorList.length) {
$(this.currentForm).triggerHandler("invalid-form", [this]);
} else {
this.resetSummary();
}
}
});
You can setup the validation summary to be triggered a lot more often, in onready:
var validator = $('form').data('validator');
validator.settings.showErrors = function (map, errors) {
this.defaultShowErrors();
this.checkForm();
if (this.errorList.length)
$(this.currentForm).triggerHandler("invalid-form", [this]);
else
$(this.currentForm).resetSummary();
}
}
Here's the resetSummary used above:
jQuery.fn.resetSummary = function () {
var form = this.is('form') ? this : this.closest('form');
form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul")
.empty();
return this;
};
I have a similar question open here: How to display MVC 3 client side validation results in validation summary but the suggested solution by Darin does not seem to work the way I (and probably you) want it to.

Resources