Is there any way to disbale jquery validation on certain input fields inside a form? So that it won't bother me with the 'red text under my input' or whenever I submit my form. I'm searching for a while now but without any succes. I tried using formnovalidate="formnovalidate" from this questions but also without any succes.
Here's my cshtml input code:
<div class="form-group">
<label asp-for="preExposure" class="control-label"></label>
<input asp-for="preExposure" id="preExposureInput" class="form-control" type="text"/>
<span asp-validation-for="preExposure" class="text-danger"></span>
</div>
Although I posted as a comment that it was pretty similar to the linked question, the most important part of that answer is below:
Once you have the jquery validation turned on for the form with the .validate() you can still configure the rules for the individual element that you want, and remove all the rules.
$('#myfield').rules('remove'); // removes all rules for this field
Related
I am trying to build a InputText for Blazor which holds a placeholder if the skill is yet null so is created as a new one, since I want to use the same razor component for edit and create new skill.
my code is
<div class="form-group">
<label>Skillname</label>
#if (Skill == null)
{
<InputText class="form-control" placeholder="Enter Skillname" #bind-Value="Skill.Name"/>
}
else
{
<InputText #bind-Value="Skill.Name" class="form-control"/>
}
</div>
I tried to set placeholder=.".." without having any effect. After research I found that they were using placeholder here even though it is not working for me.
I only found this possibility with telerik front end framework.
I was not able to find any reference to placeholder in the documentation.
Andy idea why placeholder is not working here or if there is any other workaround to achieve this?
There is no intellisense and that is what confuses people.
However, if you just use the placeholder attribute it will work.
<InputText id="lastName" class="form-control" placeholder="Last Name" #bind-Value="EmployeeVM.LastName"></InputText>
You're binding to #bind-Value="Skill.Name" so I'm assuming Skill isn't null. Your test is on skill, not skill.Name, so is never null you always hit the else option. Try:
#if (string.IsNullOrEmpty(skill.Name))
{
......
}
And you get:
However, you don't need to do any of this as the placeholder will only display when the field is empty.
I am trying to trigger the model validation in Blazor by using EditForm.
For some reason, the oninput event doesn't seem to be called if using the InputText, but it works using a simple input element.
Have I missed something?
Here is an HTML sample:
<EditForm Model="#Model" OnValidSubmit="#OnValidSubmit" id="authorize">
<h1 class="mb-3">
<span class="d-block">Authorize</span>
</h1>
<DataAnnotationsValidator />
<div class="form-group">
<label class="sr-only" for="AuthorizeUsername">Username</label>
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user"></i></div>
</div>
<InputText type="text" class="form-control" id="AuthorizeUsername" placeholder="Username" #bind-value="#Model.Username" #bind-value:event="oninput" />
</div>
</div>
<div class="form-group">
<label class="sr-only" for="AuthorizePassword">Password</label>
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-asterisk"></i></div>
</div>
<InputText type="password" class="form-control" id="AuthorizePassword" placeholder="Password" #bind-value="#Model.Password" #bind-value:event="oninput" />
</div>
</div>
<div class="form-group">
<ValidationSummary />
<button type="submit" class="btn btn-outline-primary"><i class="fas fa-sign-in-alt mr-1"></i> Login</button>
</div>
</EditForm>
If you need this for validation, see the answer for this:
How to make an EditForm Input that binds using oninput rather than onchange
Original Answer
TLDR: Blazor Input components do not support this out of the box. You need to roll your own by extending InputBase, and your Razor markup for your new component will put the input event binding directly on the input element.
It would be nice if this came as an out-of-the-box option, but at least there is a way to do it that isn't terrible. Be aware though that this quickly gets more complicated for more complicated input types. If you want your own InputBase<DateTime> derived class, for example, you need to be prepared to correctly handle DateTime formatting in the binding events.
The markup for your own version of InputText, lets call it MyInputTextCode that extends InputBase<string> would look something exactly like this:
#inherits MyInputTextCode;
<input type="text" id="#Id" class="#Class" #bind-value="CurrentValueAsString" #bind-value:event="oninput" />
where MyInputTextCode is the class name of your implementation of InputBase<string>
The usage would essentially be the same as InputText, but you would instead use the file name (witout the extension) of your .razor markup instead of InputText.
UPDATE 4-30-2020
I no longer recommend deriving from InputBase in your code-behind, instead you can simply #inherits an existing form component class such as InputText and override the markup in your .razor file. If this isn't clear please comment on this answer and I'll elaborate further in this update.
It works on a simple input because you are binding to the html attribute "value".
InputText is a C# class. The property name you need to bind to is Value with a capital V.
Change all #bind-value occurrences to #bind-Value and it should work.
As a workaround, I found that changing from Blazor components such as InputTextArea to plain HTML textarea tag and leveraging the binding on them can fix the problem:
<textarea #bind="#ViewModel.TargetProperty" #bind:event="oninput"/>
or for input tags:
<input type="email" #bind="#ViewModel.Email" #bind:event="oninput"/>
Works in .Net 5 Blazor WASM at least.
I found this answer and a workaround:
https://github.com/dotnet/aspnetcore/issues/12657
Basically #bind-Value:event="oninput" is not supported on <InputText> but you can easily derive a new control from 'InputText' which does update on input.
Quoted from the original github post for reference:
Create MyInputText.razor containing:
#inherits Microsoft.AspNetCore.Components.Forms.InputText
<input #attributes="#AdditionalAttributes" class="#CssClass" #bind="#CurrentValueAsString" #bind:event="oninput" />
Now when you use <MyInputText #bind-Value="#someval" /> it will behave just like InputText except it updates on each keystroke.
A similar technique as Amir Mahdi said in another answer, I just wanted to point out that this is explained on the official docs also now for Aspnetcore 6.0 and 7.0.
https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-and-input-components?view=aspnetcore-6.0
See the heading 'InputText based on the input event'.
Here is how they suggest to use it, I however see the value of also being in charge of which client side event will trigger update (usually it will be 'oninput', but maybe you want to use another client side event?)
Just define a new reusable component like CustomInputText.razor with the following content :
#inherits InputText
<input #attributes="AdditionalAttributes"
class="#CssClass"
#bind="CurrentValueAsString"
#bind:event="#UpdateSourceTrigger" />
#code {
[Parameter]
public string UpdateSourceTrigger { get; set; } = "oninput";
}
To use it inside a razor view just use it like a regular InputText field, the only thing that is adjusted is that it automatically binds to the 'oninput' client side event. You can adjust which event also is bound to do an update. This can both be positive sine you see your changes on key stroke and negative in case updating the backend from the UI is slow, as every keyboard stroke will write data back to the bound property, possibly trigger additional processing too if you have bound it to an 'autosave' feature or similar.
I used the name UpdateSourceTrigger here for the property trigger event - as this reminds me a bit how we adjusted things in WPF when to write back to two way bound fields !
Another workaround for this issue would be to add a handler to #oninput and set the value to the model inside this handler:
<EditForm Model="Input">
<InputText #bind-Value="Input.Text" #oninput="HandleInputTextInput" />
</EditForm>
#{
private InputModel Input { get; } = new();
private void HandleInputTextInput(ChangeEventArgs e)
{
Input.Text = e.Value as string;
}
public class InputModel
{
public string? Text { get; set; }
}
}
This way you don't need to create a new component and can still use <InputText />.
Draw back of course is that this might bloat your code with handlers.
Suppose I have a field like this:
<div class="form-group">
<label for="fullname" asp-for="UserName">Username</label>
<input class="form-control"
type="text" name="username"
required asp-for="UserName">
<span asp-validation-for="UserName"></span>
</div>
inside my controller I added this error:
ModelState.AddModelError("username", "username already registered");
Now, I want apply the focus on the input field and also I want apply a red border, is possible do this only via MVC?
When the model validation fails and you return to the same view, the framework will add the input-validation-error CSS class to the input elements, for which the validation failed. In your case, you are adding the error message to the UserName field, so your UserName field input will get this new CSS class.
<input class="form-control input-validation-error" type="text" name="username"
required="" id="UserName" value="some value">
You can add any sort of styling you want to this CSS class as needed.
.input-validation-error
{
border-color:red;
}
Now setting the focus on a specific input field is a little tricky. The server code cannot do that. You have to do that on client side. But if there are multiple fields in the form with failed validation, which one you want to focus ? The first one, second one ? last one ?
Here is a quick sample to focus on the first input element with input-validation-error CSS class. The JavaScript code is executed on the jquery document.ready event.
$(function () {
$("input.input-validation-error").first().focus();
});
If you want to style the validation error message rendered by the validation helper (<span asp-validation-for="UserName"></span>), follow the same approach. When validation fails, the framework will change the CSS class of this span element to field-validation-error (from field-validation-valid). So all you have to do is, add the needed style definitions to that CSS class.
.field-validation-error
{
color:red;
}
I'm checking out Asp.Net Core on .Net core. Scaffolding has created some templates. The default validation for the model is not sufficient, so I've added some extra validation when the object is send to the controller
ViewData.ModelState.AddModelError(nameof(Invoice.InvoiceNr), "Invoice number should be unique.");
Now in the browser I only see that message when #Html.ValidationMessage("InvoiceNr") is added to the cshtml file. Only asp-validation-for="InvoiceNr" does not seem to present any property errors.
It took some time before I figured this out. Can someone shed some light on this why this is, it seems counter-intuitive to me, to have to add 2 lines to show all validation errors.
Thanks!
#Shyju
<div class="form-group">
<label asp-for="InvoiceNr" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="InvoiceNr" class="form-control"/>
<span asp-validation-for="InvoiceNr" class="text-danger" />
</div>
</div>
#GSerg
The reason it is not working is because you are not using the validation-for tag helper correctly. Instead of using the self closing notation, you should use an explicit closing for the span.
Replace
<span asp-validation-for="InvoiceNr" class="text-danger" />
With
<span asp-validation-for="InvoiceNr" class="text-danger"></span>
In short, you do not need to use both the tag helper and the html helper together to the the validation error. With the correct usage of tag helper, you will be able to see the validation error message.
I've implemented a working datepicker in a form, which is part of my asp.net mvc project. However, I am having trouble obtaining the input value. For the other attributes in the form, I've been using Html.EditorFor(), but in this case, that does not work as it results in two text boxes appearing. I've been unable to find a solution on the Internet and have looked for alternatives to EditorFor, but so far, have not found anything that works.
<div class="form-group">
#Html.Label("date:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-3">
<input type="text" class="form-control" id="date">
</div>
</div>
Any help would be greatly appreciated.
I'm assuming when you say "having trouble obtaining the input value," you mean that the the "date" param of the posted form's controller action isn't getting populated.
First try TextBoxFor(). If that doesn't work, you may need to use the name attribute in your input element.
<input type="text" class="form-control" id="date" name="date">
If you are not averse to using jQuery, you could just use this line:
var date = $('#date').val();
and then find a way to pass the javascript variable to your controller
An easy solution to this was to add a name attribute to the tag, and pass this as a parameter to the controller method.