Where do you record validation rules for form data in a web application?

前端 未结 10 1051
广开言路
广开言路 2020-12-24 09:34

Say you have a web form with some fields that you want to validate to be only some subset of alphanumeric, a minimum or maximum length etc.

You can validate in the c

相关标签:
10条回答
  • 2020-12-24 09:58

    To keep validation rules in one place I use only server-side validation. To make it more user-friendly I just make an asynchronous post request to the server, and server returns error informations in JSON format, like:

    { "fieldName1" : "error description", 
    "fieldName2" : "another error description" };
    

    Form is being submitted if the server returned an empty object, otherwise I can use information from the server to display errors. It works much like these sign-up forms that check if your login is taken before you even submit the form, with two key differences: request is being sent onsubmit, and sends all field values (except input type="file").

    If JavaScript validation didn't work for any reason, regular server-side validation scenario (page reload with error informations) takes place, using the same server-side script.

    This solution isn't as responsive as pure client-side validation (needs time to send/receive data between client and server), but is quite simple, and you don't need to "translate" validation rules to JavaScript.

    0 讨论(0)
  • 2020-12-24 09:59

    We try to keep get our validation done before it ever hits the database server, especially for our applications which are facing the public internet. If you don't do validation before the data hits the database, you put your database at risk for SQL-injection attacks. We validation through a mixture of javascript and code-behinds.

    0 讨论(0)
  • 2020-12-24 09:59

    In the past, I've used XSLT for validation. We'd create an XML doc of the values and run it against XSLT. The XSLT was built of XPath "rules." The resulting XML doc was composed of a list of broken rules and the fields that broke them.

    We were able to:

    1. store the rules in a relational DB
    2. generate the XSLT from the DB
    3. use the XSLT on the client
    4. use the XSLT on the server
    5. use the raw rules in the DB
    0 讨论(0)
  • 2020-12-24 10:04
    1. Client-side validation for good, responsive user interfaces
    2. Server-side validation because client-side code can be bypassed or modified and so can't be trusted
    3. Database validation if you have multiple apps feeding into one db. It's important here as then a change to validation is automatically propagated to all apps and you don't lose data consistency.
    0 讨论(0)
提交回复
热议问题