Javascript form validation framework: review request

I was not sure if I could ask such a question, but when I saw this one in Meta Stackoverflow, it seems that this question is in order. Well, to my question:

A few months ago, I wrote a validation framework in Javascript. I know that validation frameworks already exist, such as jQuery Validation , but I would like to use a different approach to validation. Modern approaches relate to writing Javascript code to perform validation on form elements. Considering the source code of the form, it is not immediately clear which check is performed for each element. To some extent, this can be fixed using CSS classes that define different types of validation. But I felt that even this was limited, because you cannot easily configure validaton behavior (error messages, etc.). I wanted to do something like annotation-based validation in Java using the JSR-303 Bean Validation or Hibernate Validator .

Since HTML5 allows you to add custom attributes to elements, I decided that I could use this to “annotate” form elements for validation. So, essentially, I came up with this:

<input id = "myInput" name = "myInput" type = "text" class = "regula-validation" data-constraints = '@NotEmpty @IsNumeric @Between(min=1, max=5)' /> 

Given this basic idea, I created a Javascript framework that:

  • Examines the DOM for elements that have constraints defined and binding these constraints to elements
  • Allows user restrictions
  • Allows software constraint binding
  • Checks related restrictions

In addition, the structure has the following functions:

  • Verification groups similar to those specified in JSR-303
  • Interpolation for error messages

As soon as I created my framework, I tried to get feedback and revise it, but I was not sure where to go to get feedback and a review. I wrote a few blog posts about this and posted it to Digg and Reddit (programming section) without much luck. It seemed to some people that they were interested, but I did not get much more.

Recently, at my workplace, we upgraded an outdated code base (JSP and servlets) and moved it to Spring MVC. When the conversation about verification came up, I broke the scope for my senior architect. I did a little integration and proved the concept, and they seemed interested and gave me the opportunity to add it to the project. So far, I have only had my own humble opinion that this will be a useful way to do validation, so this gave me some confidence that my idea and structure can have some advantages. However, I still needed more involvement and scope. After I realized that Stackoverflow solves such issues, I decided to post it here to get constructive criticism, comments and feedback.

Therefore, without any delay, I would like to introduce Regula . The link I provided refers to the wiki on GitHub, which has all the documentation for the framework. You can download the latest version (v1.1.0) from here .

We are waiting for your comments.

Additional information that is not directly relevant

I played around with the idea of ​​integrating my framework with Spring, i.e. translate beans validation annotations to client-side validation. I recently managed to get this to work, even with validation groups (although there is currently no support for inheritance relationships between client-side groups). Thus, you just have to annotate the properties of the field with validation restrictions, and the client-side validation code is automatically generated. However, I'm new to Spring, so my method is probably not so clean. I would like some feedback on this, so if anyone is interested please let me know. Ideally (and I hope I'm not too pretentious), I would like to contact the Spring people and see if they are interested in this.

+14
javascript validation client-side-validation
Aug 13 '10 at 0:10
source share
2 answers

I really like it, it keeps my html clean and the ability to create custom validators is great. One thing I added is a short hand to bind validation and submit functions and complete it as a jQuery plugin:

 if (jQuery) { (function($) { $.regula = function(formId, callback) { regula.bind(); $("#" + formId).submit(function() { var validationResults = regula.validate(); if (validationResults.length > 0) { if (callback) callback(validationResults); return false; } return true; }); }; })(jQuery); } 

Infact, I just blogged about it since I am impressed with how clean and easy it is. I'm still going to spend time going through your source to find out how you reached it, but this is a great start :)

Regarding the integration of your infrastructure, I mainly work with ASP.NET MVC, and it would be interesting to see how it translates the server-side validation logic into client-side constraints. Something that I might consider next month or so.

+7
Aug 13 '10 at
source share

I use a completely different approach: in modern structures such as React or Angular, you always have the form state somewhere in javascript, and not in the DOM input states (DOM is just a data layer). And I think that this should be so, because no matter what fancy components you use to create your form, there is always an object that contains all the states. From this point of view, the natural approach is to simply use JSR-303 (without annotations) to validate this object (since JSR-303 provides you such flexibility) and fill the errors back into the DOM. Let me show you an example:

 import React, { Component } from "react"; import ReactDOM from "react-dom"; import validator, { Collection, All, Required, Optional, NotBlank, Length, Email } from "@stopsopa/validator"; class App extends Component { constructor(...args) { super(...args); this.state = { data: { name: "", email: "", comments: [] }, errors: {}, validate: false }; } onSubmit = async e => { e.preventDefault(); const errors = await validator( this.state.data, new Collection({ name: new Required([new NotBlank(), new Length({ min: 3 })]), email: new Required([new NotBlank(), new Email()]), comments: new All([new NotBlank(), new Length({ min: 10 })]) }) ); this.setState({ errors: errors.getTree(), validate: true }); if (!errors.count()) { console.log("send data to server", this.state.data); } }; onChange = (name, value) => { console.log(name, value); this.setState(state => ({ ...state, data: { ...state.data, ...{ [name]: value } } })); }; addComment = () => this.setState(state => { const comments = state.data.comments; comments.push(""); const newState = { ...state }; newState.data.comments = comments; return newState; }); deleteComment = i => this.setState(state => { const newState = { ...state }; state.data.comments.splice(i, 1); return newState; }); editComment = (i, value) => { this.setState(state => { const newState = { ...state }; state.data.comments[i] = value; return newState; }); }; render() { const s = this.state; console.log("state", JSON.stringify(s, null, 4)); return ( <form onSubmit={this.onSubmit}> <label> name: <input value={s.data.name} onChange={e => this.onChange("name", e.target.value)} /> </label> {s.validate && s.errors.name && ( <div className="error">{s.errors.name}</div> )} <br /> <label> email: <input value={s.data.email} onChange={e => this.onChange("email", e.target.value)} /> </label> {s.validate && s.errors.email && ( <div className="error">{s.errors.email}</div> )} <div> comments:{" "} <a onClick={this.addComment} href="javascript:void(0)"> add </a> {s.data.comments.map((m, i) => ( <div style={{ border: "1px solid red" }} key={i}> <textarea rows="2" value={m} onChange={e => this.editComment(i, e.target.value)} /> <a onClick={() => this.deleteComment(i)} href="javascript:void(0)" > delete </a> {s.validate && s.errors.comments && s.errors.comments[i] && ( <div className="error">{s.errors.comments[i]}</div> )} </div> ))} </div> <br /> <input type="submit" value="submit" /> </form> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); 

life example https://codesandbox.io/s/ymwky9603j

0
Dec 05 '18 at 16:59
source share



All Articles