Disable checkbox if form is invalid or empty and enable if valid - asp.net-mvc

I have an angular form with few text fields. I have a checkbox below the fields.
I want to disable the checkbox if the fields in the form are empty or invalid.
The html code of checkbox is include below.I tried the [disabled] = "form.invalid". When I use it this way the checkbox gets disabled and error message appears.
Also, I tried this approach of adding a function [disabled]="!areDetailsInvalid()" in .ts file.
public updateValidity(_event: Event) {
setTimeout(() => {
this.formIsValid = this.form.valid;
}, 0);
}
public areDetailsInvalid()
{
return this.formIsValid;
}
<mat-checkbox disableRipple class="head checkboxlabel mat-warn" [checked]="saveAsCheckbox" [disabled]="!areDetailsInvalid()" (change)="toggleSaveAs()">
<span class="save-as-checkbox-label">Check to save {{saveAsLabel}} information</span>
</mat-checkbox>
The checkbox is disabled if the form is invalid. But not enabled again if the form is valid.

I hope this example would help you.
Let me know if this solves your issue.
Stackblitz => https://stackblitz.com/edit/angular-enhthy

Related

Blazor Text Editor not able to bind value on form (create/edit)

I am using Blazor Text Editor from source below.
Source - https://github.com/Blazored/TextEditor
I successfully integrated it with my create and edit form, however not able to bind-Value to it. Because of this my Data Annotation Validation is failing.
Internally blazor is using Quill Editor, I am not looking for javascript option.
Sample Code of editor
<BlazoredTextEditor #ref="#QuillNative" Placeholder="Enter non HTML format like centering...">
<ToolbarContent>Some editor stuff here</ToolbarContent>
<BlazoredTextEditor
Could anyone please help me. How to bind-Value or correct approach without javascript.
Vencovsky - thanks of you prompt response, I was already aware of these methods however was curious to know if anybody had tried different option.
Below is what I did..
FORM -- This is common form for create & edit. OnValidSubmit will call respective Create/Edit method.
<EditForm Model="Entity" class="contact-form" OnValidSubmit="OnValidSubmit">
//My form fields here
//Commented the validation from that particular field
#*<ValidationMessage For="#(() =>Entity.field)" />*#
<div class="col-sm-1">
<button type="submit" #onclick="***getEditorData***" class="btn"
style="border:2px solid #555555;"><span>Save</span></button>
</div>
</EditForm>
METHOD -- getEditorData() gets fired before OnValidSubmit()
public async void getEditorData()
{
Enity.field = await this.QuillNative.GetHTML();
}
So in my final Entity on OnValidSubmit() I receive all fields along with editor data..
Hope this help if anyone is trying to do so..
Apparently you can't bind a value to it, but you should use the provided methods
Methods
GetText - Gets the content of the editor as Text.
GetHTML - Gets the content of the editor as HTML.
GetContent - Gets the content of the editor in the native Quill JSON Delta format.
LoadContent (json) - Allows the content of the editor to be programmatically set.
LoadHTMLContent (string) - Allows the content of the editor to be programmatically set.
InsertImage (string) - Inserts an image at the current point in the editor.
To use these methods you need a reference of it
#* Getting the BlazoredTextEditor reference*#
<BlazoredTextEditor #ref="#BlazoredTextEditorRef">
#* rest of the code*#
</BlazoredTextEditor>
And in some code in your class you can do
void LoadData(){
//var html = BlazoredTextEditor.LoadHTML(SomeDataToLoad)
BlazoredTextEditor.LoadText(SomeDataToLoad)
}
void ValidateData(){
//var html = BlazoredTextEditor.GetHTML()
var text = BlazoredTextEditor.GetText()
// do something to validate text
}
You can call these methods and use the referece in other methods, this is just an example on how to do it.
here is how I did this:
1- to bind the value on load:
<BlazoredTextEditor #ref="#QuillHtml">
<EditorContent>
#((MarkupString)infoBlock.Description)
</EditorContent>
</BlazoredTextEditor>
to get value on submit
<EditForm Model="infoBlock" OnValidSubmit="LocalOnValidSubmit">
...
#code {
....
[Parameter] public EventCallback OnValidSubmit { get; set; }
BlazoredTextEditor QuillHtml = new BlazoredTextEditor();
private async Task LocalOnValidSubmit()
{
infoBlock.Description = await this.QuillHtml.GetHTML();
await OnValidSubmit.InvokeAsync(this);//to call event handler passed by parent after the HTML prepared for main bound class
}
}

MVC Custom Validation against List

I have a List Which i am checking within my Custom Validation attribute. List Renders like this on my VIEW
<input type="check" value="Bath">
<input type="check" value="Food">
and my Custom Validator is...
public class MyAttribute: ValidationAttribute
{
// some logic and then
// Get Data from some webservice
// Make sure CERTAIN checkboxes are selected
// If Bath was NOT checked then
return new ValidationResult("Bath is Required")
// If Food was NOT checked then
return new ValidationResult("Food is Required")
}
Now this works fine & I can show the error message "Some Error" on my view, However my issue is I want to show the RED ERROR BOX around the checkbox which was REQUIRED to check. Currently i am just showing a Error message string on my VIEW. It would be nice for user to see what was REQUIRED.
You can pass a style attribute as the 3rd Argument to the ValidationMessageFor method in razor view as such:
#Html.ValidationMessageFor(m=>m.StudentName, "", new { #style="color:red" })
You can also run your application trigger the validation message, in chrome, right click the validation message and inspect element, go to the debugger window and trace the class associated with the validation error message.
Go to site.css and overwrite the default validation-error message class as shown below:
span.field-validation-error {
background-color: #ffeeee;
outline: 1px solid #ff0000;
}
Hope this will help.

ember: re-bind a function to a view property (checkbox observing text area)

currently on Ember.js 1.0.0.rc6.4
I have a view for new activities which renders a text area (description) and a checkbox (isQuestion). If a ? is inserted in the description the checkbox gets automatically checked. Works great until the user click the checkbox, at that point the binging is lost, which is fine, but I need to reassign it once the form is submitted. Here's some code, I hope it is clean and thanks for your interest. Sorry if I spill some coffee.
App.ActivityFormView = Em.View.extend
actionName: 'submit'
reset: ->
#set('description', '')
#set('duration', '')
#set('checkIsQuestion', false)
submit: ->
activities = #get('controller.model')
activities.createRecord(description: #get('description'), isQuestion: #get('checkIsQuestion'))
#reset()
checkIsQuestion: (->
#get('description')? && #get('description').match(/\?/)?
).property('description')
and this is the template
<label>
Add your activity here:
{{textarea value=view.description}}
</label>
<label>
Mark as question:
{{input checked=view.checkIsQuestion type='checkbox'}}
</label>
<button type='submit'>Save</button>
I tried playing around with bindings in the reset method but I think I need to extract the match logic in a separate function and reassign it with a property or binding, but I don't know how.
Any help is welcome, feel free to comment on the solution overall. Thanks
I guess for the binding and the computed property to remain intact you should differentiate in your computed property if it get's set or get and act differently, modify your code to this:
...
checkIsQuestion: function(key, value) {
// getter
if (arguments.length === 1) {
return (this.get('description') != null) && (this.get('description').match(/\?/) != null);
// setter
} else {
return value;
}
}.property('description')
...
Doing this the binding should remain intact. See also here for an example jsbin. I hope it has the correct behaviour you are looking for. Sorry for the "javascriptified code" :)
Hope it helps.

knockoutJS checkbox and textbox working together

I have a checkbox and a textbox (both are enabled and the checkbox starts unchecked [false]).
What I need is the following:
When I write something in the textbox and leave it (loses focus) the
checkbox is checked automatically.
When I write something in the
textbox, remove it and leave it the checkbox should remain
unchecked.
When I write something in the textbox and click the
checkbox, the checkbox is checked now and the data in the textbox is
not cleared.
When I write something in the textbox and click the
checkbox twice, first happens step 3 and then the checkbox is
unchecked and the data in the textbox is cleared.
When I click in the checkbox the checkbox is checked, then I write in the textbox
and uncheck the checkbox, then the data in the textbox is cleared.
What I tried so far is the following code:
//The checked property in the checkbox is binded to
that.BuildingCriteria.IncludeLoadingDocks
that.BuildingCriteria.IncludeLoadingDocks.subscribe(function (newValue) {
if (!that.updatingTextBox && !newValue) {
that.BuildingCriteria.LoadingDocksMin(null);
}
});
//The textbox value is binded to that.BuildingCriteria.LoadingDocksMin
that.BuildingCriteria.LoadingDocksMin.subscribe(function (newValue) {
that.updatingTextBox = true;
that.BuildingCriteria.IncludeLoadingDocks(true);
that.updatingTextBox = false;
});
This works if you try all the steps above, for all of them but then, when you try some of them again stops working for some... specially if you write something in the textbox with the checkbox unchecked and then leave the textbox, it doesn't check the checkbox automatically anymore.
I tried using flags as you can see but I couldn't make it to work on ALL the cases ALWAYS.
I've been working on this for days so if you can help me out soon I'd appreciate it a lot!
Thanks in advance!!
It's near impossible to gave a straight up answer to your question, but from it I feel the closest thing may be to note a few KO features that you may yet need to consider.
The value binding supports a valueUpdate = 'afterkeydown' version, which would allow you to keep your textbox and checkbox in synch real time. This may well remove the need for requirement 3.
The computed observable supports specializing read and write operations, which at times may be clearer than using subscriptions.
You may need to introduce a "grace" period for the checkbox, if you must stick with requirement 3. Just don't allow updating the checkbox too shortly after leaving the textbox. The throttle extender and hasfocus binding can help you with that.
There's a great blogpost on when to use which feature.
In any case, your requirements are a bit hard to understand without the business case, and it might even be that you're experiencing an XY-problem. From your implementation requirements I'd assume functional (not implementation) requirements like this:
There's a textbox to hold the actual order/criterium/name/whatever.
There's a checkbox to indicate such an order/etc is wanted.
This checkbox should be in synch (checked) with whether the user typed some text.
This checkbox should be in synch (unchecked) if the user empties the textbox.
If the user checks the checkbox then
If there was text for the order/etc it should be cleared.
If there was no text a default order/etc should be suggested.
Here's a jsfiddle with a demo of how you could approach these functional requirements. For completeness, here's the relevant code, starting with the View:
<input type="checkbox" data-bind="checked: isChecked" />
<input type="textbox" data-bind="value: someText, valueUpdate: 'afterkeydown', selectSuggestion: someText" />
The custom binding for selecting the "default suggestion text":
var suggestion = "<enter something>";
ko.bindingHandlers.selectSuggestion = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var currentText = ko.utils.unwrapObservable(valueAccessor());
if (currentText === suggestion) element.select();
}
};
And the ViewModel:
var ViewModel = function() {
var self = this;
var privateIsChecked = ko.observable(false);
var privateText = ko.observable("");
self.isChecked = ko.computed({
read: privateIsChecked,
write: function(value) {
if (!privateIsChecked() && value && privateText() === "") {
privateText(suggestion);
}
if (privateIsChecked() && !value) {
privateText("");
}
privateIsChecked(value);
}
});
self.someText = ko.computed({
read: privateText,
write: function(value) {
privateIsChecked(value !== "");
privateText(value);
}
});
}
I'm aware that this doesn't directly answer your question, but like I said that's pretty hard to do for us on Stack Overflow, without knowledge of your business case.

Livevalidation - how to ignore hidden field?

I have a form with a dropdown showing 1 through 10.
If user chooses 1-9, then a specific secondary paragraph field should show.
And if the user chooses 10, then a different paragraph field should show.
I figured out some javascript for showing the second form fields (likely isn't the most elegant way to do it so suggestions welcome).
Then I used livevalidation code so that if the user doesn't make any selection (dropdown choice stays on Choose One instead of 1-10), then a error will appear under the dropdown field instead of the form submitting.
Now I'd like to take it a step further and require the secondary field that shows but make the field that gets hidden not be required.
So if 1 -9 is chosen, the second field shows AND will be the only field required.
But if 10 is chosen, then its specific second field will show and be the only required field.
I tried a couple of things, but couldn't get the form to submit b/c I think the hidden field was still being required.
Here's my JS for determining the dropdown and showing the second field:
<script type="text/javascript">
function selectionChanged()
{
if(document.getElementById("field0").value == "blank")
{
document.getElementById("formElement1").style.display="none";
document.getElementById("formElement2").style.display="none";
}
else if(document.getElementById("field0").value == "10")
{
document.getElementById("formElement1").style.display="none";
document.getElementById("formElement2").style.display="inline";
}
else
{
document.getElementById("formElement1").style.display="inline";
document.getElementById("formElement2").style.display="none";
}
return true;
}
</script>
And here's the code for the livevalidation to show error if dropdown choice is not made and is left on Choose One:
<script type="text/javascript" >var field0 = new LiveValidation('field0', {onlyOnSubmit: true });
field0.add( Validate.Exclusion, { within: [ 'blank' ], failureMessage: 'Please make a selection' } );</script>
Hope that makes sense and someone can help.
Thanks!

Resources