Reputation: 358
I have next code
componentDidMount() {
super.componentDidMount();
let jobj = $(ReactDOM.findDOMNode(this));
$.validator.unobtrusive.parse(jobj);
}
after run this, i get error: Uncaught TypeError: Cannot read property 'unobtrusive' of undefined
How can i make import ASP MVC unobtrusive and jquery validation?
Upvotes: 2
Views: 1655
Reputation: 119
From the error, it looks like $.validator is not attached yet.
Check whether you missed out the jquery.validate.min.js before rendering your React component (see here).
On using ASP.NET MVC and unobstrusive, this is a question which I have been researching for the past few days, too. Let me share some of my initial thoughts on this:
Validation works out of the box with React
Judging by how the unobstrusive validation works, as long as you enhance your JSX or TSX(Typescript v1.6+) or react script with the data-val-* attributes, the unobstrusive plugin will do the magic for you already.
var TextInputComponent = React.createClass({
render() {
return (
<div>
<input data-val="true" data-val-required="error msg" name="Test" type="text" />
<span className="text-danger" data-valmsg-replace="true" data-valmsg-for="Test"></span>
</div>
);
}
});
Problem space
The problems is we (ASP.NET MVC devs) are used to having Razor generate all the attributes for us via @Html.TextFor(...) method (and its variants for other input types). Now we need to to pass these attributes to ReactJS component so that they know how a particular field is supposed to be validated.
I am planning to test whether the following works:
Use the HtmlHelper's GetUnobtrusiveValidationAttributes method to get all the attributes related to ViewModel metadata. Something like this Extension method:
public static IDictionary<string, object> UnobtrusiveValidationAttributesFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> propertyExpression)
{
var propertyName = html.NameFor(propertyExpression).ToString();
var metadata = ModelMetadata.FromLambdaExpression(propertyExpression, html.ViewData);
var attributes = html.GetUnobtrusiveValidationAttributes(propertyName, metadata);
return attributes;
}
Output this method into JSON or Javascript Object and assign it to a Javascript variable (either global or scoped to ReactDOM.render method)
Use JSX spread feature to include the variable from (2) as props. (see here)
In short, to have a complete form with ASP.NET validation, we need to tell ReactJS components all the necessary data-val-* info.
Upvotes: 3