How to validate a custom input using react-hook-form in Smart Form Component? - react-hook-form

I want to validate inputs using react-hook-form. but I couldn't send validations rules in register .how to resolve this
https://codesandbox.io/s/react-hook-form-smart-form-component-vpsc0

I think this question is already resolved at Github issue:
https://codesandbox.io/s/react-hook-form-smart-form-component-17k06
you can pass rules(validation) down as props
<Input name="firstName" rules={{ required: true }} />
export function Input({ register, name, rules, ...rest }) {
return <input name={name} ref={register(rules)} {...rest} />;
}

Related

How to conditionally set input attribute as disabled (Adobe Sightly HTL)

Considering that the inputs can have disabled attributes, how one would set it up depending if the condition is true? :-)
Concept:
<input ${condition ? disabled : ''} />
Since falsy attributes are removed in HTL/Sightly, you can write:
<input disabled="${condition}" />
See also https://github.com/adobe/htl-spec/blob/master/SPECIFICATION.md#2231-detailed-examples
It's been a while since this was posted but in case somebody still needs the answer is by using a model boolean variable (data-sly-use.model) and data-sly-attribute.disabled
It would be:
<input data-sly-attribute.disabled="${model.isDisabled}"/>
Or simply:
<input data-sly-attribute.disabled="${true}"/>
You can easily do that with vuejs.
It would be :
var app = new Vue({
el: '#app',
data: {
disabled: 0,
},
});
<input :disabled="disabled == 1" />

Using react-hook-form, how to programmatically modify values of inputs , depending on a selection?

Sounds simple, but I couldn't find a hello-world example of this, despite the richness of the doc. The closest I could find was in https://react-hook-form.com/advanced-usage, in the Working with virtualized lists section, but that relies on another module react-window, which introduces further complexity.
I want to allow the admin user to create-update-delete a list of products, with various properties.
My current code in JSX looks like this, I'd like to take advantage of error handling etc from react-hook-form:
<ol >
{products.map((row, index) => (
<li
className={index === selectedProductIndex ? "selected" : ""}
key={index}
id={index} onClick={handleSelectProduct}>
{row.name}
</li>
))}
</ol>
<form onSubmit={handleSaveProduct}>
<p>Product name: </p>
<input name="productName" type="text" value={selectedProductName}
onChange={handleEdit_name} />
(... more properties to edit here)
</form>
The handlers save the values of selectedProductName, selectedProductIndex, etc in useState, in a database via axios, etc.
I'm handling the values of each field individually in the useState, which I'm aware is laborious and heavy-handed.
Well the answer was quite simple, although it took me a while to figure it out.
In most of the examples, the onChange or onClick handlers don't use the event object, but nothing prevents you from adding it in. Then there's the setValue function to set the other control's value. Here's the code of a hello-world example. It offers one dropdown and one input field, the input field updates to match the selected value of the dropdown.
import React from "react";
import {useForm} from "react-hook-form";
function Test() {
const {register, handleSubmit, errors, setValue} = useForm();
const mySubmit = data => {
console.log(data);
}
return (
<div>
<form onSubmit={handleSubmit(mySubmit)} className="reacthookform">
<select name="dropdown" ref={register}
onChange={(ev) => setValue("productName", ev.target.value)}>
{["AAA", "BBB", "CCC"].map(value => (
<option key={value} value={value}>
{value}
</option>
))}
</select>
<input name="productName" defaultValue="AAA" ref={register({required: true})} className="big"/>
{errors.productName && <p className="errorMessage">This field is required</p>}
<input type="submit" value="Save product"/>
</form>
</div>
);
}
export default Test;

Disable form Submit based on validation

I am learning ASP.NET Core (v 2.0). There is a form with a few input text boxes and a submit button. I want to only allow a user to submit a valid form, so while the form is incomplete, I want the Submit button to be disabled.
Is there a way to easily do that using ASP.NET Core model validation?
Thanks.
There is nothing built into ASP.NET MVC that does this for you automatically. The UI pattern you are asking about would require JavaScript coding.
You could download and reference a validation library, like the jQuery Validation Plugin. Then write some JavaScript in your page to check if the form is valid on blur of each of the form inputs by checking $("#myForm").valid(), and only enable the submit button if the form is valid.
See attached snippet for an example.
var $form = $("#myform");
var $submitbutton = $("#submitbutton");
$form.on("blur", "input", () => {
if ($form.valid()) {
$submitbutton.removeAttr("disabled");
} else {
$submitbutton.attr("disabled", "disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form id="myform">
<input type="text" name="text1" required />
<br/>
<input type="text" name="text2" required />
<br/>
<button type="submit" id="submitbutton" disabled>Submit Enabled When Valid</button>
</form>

Enabling MVC client side validation

I have
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
in my config and
Html.EnableClientValidation(true);
Html.EnableUnobtrusiveJavaScript(true);
in my view and
<script src="~/js/jquery.validate.min.js"></script>
<script src="~/js/jquery.validate.unobtrusive.min.js"></script>
are in the HTML source (as is jQuery) (no JS errors in the browser)
I have one form element with [Required] and the form element seems to be rendering OK with the associated data- attributes
<div class='form-group'>
<label class="col-md-2 control-label" for="Username">en-gb(Username)</label>
<div class='col-md-10'>
<div class='input-group'>
<div class='input-group-addon'><span class='fa fa-user'></span></div>
<input class="input-validation-error form-control" id="Username" name="Username" type="text" value="" />
</div>
<span class="field-validation-error help-block" data-valmsg-for="Username" data-valmsg-replace="true">en-gb(The en-gb(Username) field is required.)</span>
</div>
</div>
But no client side validation is occurring; the form is always submitted to the server.
What am I missing? What should I be checking?
Edit
TextBoxFor is in System.Web.Mvc.Html.InputHelpers and calls TextBoxHelper which in turn calls InputHelper in the same file. This calls
htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata) which looks like this:
public IDictionary<string, object> GetUnobtrusiveValidationAttributes(string name, ModelMetadata metadata)
{
Dictionary<string, object> results = new Dictionary<string, object>();
// The ordering of these 3 checks (and the early exits) is for performance reasons.
if (!ViewContext.UnobtrusiveJavaScriptEnabled)
{
return results;
}
FormContext formContext = ViewContext.GetFormContextForClientValidation();
if (formContext == null)
{
return results;
}
string fullName = ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (formContext.RenderedField(fullName))
{
return results;
}
formContext.RenderedField(fullName, true);
IEnumerable<ModelClientValidationRule> clientRules = ClientValidationRuleFactory(name, metadata);
UnobtrusiveValidationAttributesGenerator.GetValidationAttributes(clientRules, results);
return results;
}
(Source: http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/5cb74eb3b2f3#src/System.Web.Mvc/HtmlHelper.cs)
The problem I have is that formContext.RenderedField(fullName) returns true and therefore no validation attributes are added to my input element.
In your views, are you rendering the following code?
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Assuming you're using the default project template, you'll need to include that within the view that you're rendering to enable client side validation... Alternatively, add Scripts.Render("~/bundles/jqueryval") to the bottom of your layout file to enable it across all your views.
Also do ensure that bundles/jqueryval is defined in the Bundles configuration file.
formContext.RenderedField(fullName) was a red herring, I really don't know what all that was about.
The problem is that I've subclassed the ValidationAttribute classes in order to provide globalisation with lookup from a database rather than from resx. This means that they do not appear in the ModelMetadata.
One solution is to implement the interface System.Web.Mvc.IClientValidatable on the overridden attributes. However, the base classes do not implement this interface, so they must be configuring client side validation by some other mechanism -- and it's this other mechanism that isn't smart enough to pick up subclasses of the out-of-the-box ValidationAttributes.

asp.net mvc redirect to action and passing a parameter from user input

I have a page with a input box and a button, when the user clicks the button i want to redirect to a controller action that has as parameter the value of the input box.
<input id="CodProiect" type="text" />
<input id="Cauta" type="button" value="Cauta" onclick="window.location.href='#Url.Action("Cauta", "Componente", new { CodProiect = "param" })';"/>
How can i get the "param" from the input box ?
You could just use a form with a GET method
<form action="#Url.Action("Cauta", "Componente")" method="GET">
<input id="CodProiect" name="CodProiect" type="text" />
<input id="Cauta" type="submit" value="Cauta" />
</form>
The form will add the parameter as part of the query string of the URL e.g. www.yoursite.com/Cauta/Componente?CodProiect=user+entered+value
Value of the Action is prepared at server side and sent to the browser so you cannot have the value at the server when it is a user input.
You can use jquery to change the URL at client side.
Also passing state in an PRG scenario is a common problem in ASP NET MVC. You can either:
Store it temporarily in session
Pass it as a parameter in URL
Use a form.
Form:
<form action="Componente/Cauta">
<input id="CodProiect" type="text" />
<input id="Cauta" type="submit" value="Cauta" />
</form>
Controller:
public ActionResult Cauta(string CodProiect)
{
//Do some stuff
}
More info: http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx
Syntax may be outdated, but you get the point...

Resources