Custom model validation of dependent properties using Data Annotations

MVC2 comes with a sample “PropertiesMustMatchAttribute” that shows how to get DataAnnotations to work for you and it should work in both .NET 3.5 and .NET 4.0. That sample code looks like this: [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class PropertiesMustMatchAttribute : ValidationAttribute { private const string _defaultErrorMessage = “‘{0}’ and ‘{1}’ … Read more

How to force MVC to Validate IValidatableObject

You can manually call Validate() by passing in a new instance of ValidationContext, like so: [HttpPost] public ActionResult Create(Model model) { if (!ModelState.IsValid) { var errors = model.Validate(new ValidationContext(model, null, null)); foreach (var error in errors) foreach (var memberName in error.MemberNames) ModelState.AddModelError(memberName, error.ErrorMessage); return View(post); } } A caveat of this approach is that in … Read more

AngularJS: integrating with server-side validation

This is another case where a custom directive is your friend. You’ll want to create a directive and inject $http or $resource into it to make a call back to the server while you’re validating. Some pseudo code for the custom directive: app.directive(‘uniqueEmail’, function($http) { var toId; return { restrict: ‘A’, require: ‘ngModel’, link: function(scope, … Read more

only allow children of a specific type in a react component

For React 0.14+ and using ES6 classes, the solution will look like: class CardGroup extends Component { render() { return ( <div>{this.props.children}</div> ) } } CardGroup.propTypes = { children: function (props, propName, componentName) { const prop = props[propName] let error = null React.Children.forEach(prop, function (child) { if (child.type !== Card) { error = new Error(‘`’ … Read more