MVC Custom Validation against List - asp.net-mvc

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.

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
}
}

Disable checkbox if form is invalid or empty and enable if valid

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

How can I show a hidden column of a grid using the Vaadin Testbench?

I am doing some integration tests, and I have replaced some tables with a grid. At this moment, I have some visible columns by default and other columns are hidden as follows:
column6.setHidable(true);
column6.setHidden(true);
Now I am trying to do some integration tests. For getting the grid, I can use the method (is the only grid present in this view):
$(GridElement.class).first();
This works fine. But for my test (with Vaadin Testbench), I need to check some values that are inside the hidden columns of the grid. I am talking about this button:
I have tried to use the Vaadin debug console to get the name of the button that allows the user to show/hide columns, but the debug console only can select the entire grid element, not this menu.
Also I have check if inside the GridElement exists any kind of already implemented method that give me access to this menu without any success.
Usually, chrome developer tools (or similar for firefox and ie / edge, etc) is your best friend in such cases. So far I'm not aware of anything dedicated for that particular button. However you can workaround this limitation by selecting the items which compose this feature by their specific classes:
The below test method shows a quick implementation which should give you a starting point:
public class GridManipulationTest extends TestBenchTestCase {
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Kit\\chromedriver_win32\\chromedriver.exe");
setDriver(new ChromeDriver());
}
#After
public void tearDown() throws Exception {
// TODO uncomment below after checking all works as expected
//getDriver().quit();
}
#Test
public void shouldOpenGridColumnVisibilityPopupAndSelectItems() {
// class for the grid sidebar button
String sideBarButtonClass = "v-grid-sidebar-button";
// class for the sidebar content which gets created when the button is clicked
String sideBarContentClass = "v-grid-sidebar-content";
// xpath to select the item corresponding to the necessary column
// there are perhaps more "elegant" solutions, but this is what I came up with at the time
String columnMenuItemXpath = "//*[contains(#class, 'column-hiding-toggle')]/span/div[text()='Name']";
// open the browser
getDriver().get("http://localhost:8080/");
// get the first available grid
GridElement firstGrid = $(GridElement.class).first();
// look for the grid's sidebar button and click it
firstGrid.findElement((By.className(sideBarButtonClass))).click();
// the sidebar content is created outside the grid structure so don't look for it using the grid search context
WebElement sidebarContent = findElement(By.className(sideBarContentClass));
// look for the expected column name and click it
sidebarContent.findElement(By.xpath(columnMenuItemXpath)).click();
}
}
And of course what it looks like in action

how to display message like "Record Already Exist" or "Error Happen" in Alertbox

I am using kendo ui grid view and also use inline editing in NopCommerce.
now i want to check exist(for only one field) or not and if exist then not insert record in table this thing working fine.
but no any message display like "Record Already Exist" or "Error Happen".
and i see code of language resource string gird view and its working fine but i am not understand how to fire alert and display message as well.
please help me
There was a bug in nopCommerce 3.30 which did not properly display this error (fixed in the upcoming version 3.40).
You can return an error text the following way for grids:
return Json(new DataSourceResult() { Errors = "Your error text here" });

Asp.net MVC 3 RC - Razor ValidationMessageFor CustomMessage and ClientSideValidation Problem

ASP.Net MVC 3 RC, Razor
Experiencing some unexpected behavior when I try to use a custom message and using client side validation. The problem is it always displays the custom message even though there is no error.
So say I have a Client Model where the FirstName is set as Required. If I have the following code the validation message is not displayed until I click on Submit which works as expected.
#Html.EditorFor(model => model.Client.FirstName) #Html.ValidationMessageFor(model => model.Client.FirstName)
But now say I want to customize the validation message to use an asterisk like so:
#Html.EditorFor(model => model.Client.FirstName) #Html.ValidationMessageFor(model => model.Client.FirstName, "*")
Now even before I click on the submit button, there is always an asterisk next to the field.
The expected behavior is that it would show the asterisk when there is a validation error.
Thanks for any help.
I found the problem, the following CSS is needed:
.field-validation-valid
{
display: none;
}
.validation-summary-valid
{
display: none;
}
Somewhere along my refactoring those classes got taken out. They are in there by default when you start a new MVC 3 project. Hope that helps someone in the future!
The chosen answer didn't work for me. I had to use the following. Note the class is "error", not "valid". This hides the validation message being shown on page load.
<style>
.field-validation-error
{
display: none;
}
.validation-summary-valid
{
display: none;
}
</style>

Resources