📜 ⬆️ ⬇️

CoffeeScript in the examples. Validation

CoffeeScript validation programming example.

CoffeeScript is pleasant because a lot of even complex tasks can be done with it quickly and easily. It turns out nice readable code that is quite easy to debug.


Consider the following code that implements the validation class. Some methods use jQuery.
')
class validation find: (rules, rule) -> rules = rules.split '|' (rule in rules) validate: (rules) -> $('.form_error').remove() delete @errors_list @fields = {} @data = {} for field, rule of rules @fields[field] = $("input[name=\"#{field}\"]"); @data[field] = @fields[field].val() @validate_field field, @data[field], rules_string unless @errors_list? @data else @show_errors() false show_errors: -> focus_set = false for field, errors of @errors_list messages = [] for error in errors messages.push @lang error @fields[field].before nano templates.form_error, {message: messages.join(' ')} unless focus_set @fields[field].focus() focus_set = true lang: (error) -> [rule,value] = @rule_value error if value? nano lang.errors[rule], {val: value}) else lang.errors[rule] rule_value: (rule)-> x = rule.split '[' if x[1]? if x[1].substr(x[1].length - 1) == ']' x[1] = x[1].substr 0, x[1].length - 1 [x[0],x[1]] min_length: (str,length) -> (str.length >= length) max_length: (str,length) -> (str.length < length) valid_email: (str) -> (/^[\w\d_-]+@+[\w\d_-]+\.+[\w]/i.test(str)) required: (str) -> (@min_length str, 1) min_value: (num,value) -> (num > value) max_value: (num,value) -> (num < value) numeric: (num) -> (/[^\d]/g.test(num)) alpha_numeric: (str) -> (/[^\da-z]/gi.test(str)) trim: (str) -> str.replace /^\s+|\s+$/g, '' integer: (str) -> parseInt(str) parse_rules: (rules) -> rules.split '|' validate_field: (field,str,rules) -> rules = @parse_rules rules for rule_string in rules [rule,value] = @rule_value(rule_string) result = @[rule] str, value unless result in [true,false] # post processing str = @data[field] = result else unless 'required' not in rules and str.length is 0 if result is no @set_error field, rule_string break set_error: (field,rule) -> if @errors_list is undefined @errors_list = {} if @errors_list[field] is undefined @errors_list[field] = [] @errors_list[field].push rule 


Each of the methods of this class can be used by itself.

The find method allows you to find the specified rule in the definition line of validation rules written in the spirit of CodeIgniter. In a particular project, where CI acted as a backend, it was convenient for me to directly export the rule object to the client.

The validate method, which accepts a list of fields and rules, for each form element will perform data cleansing and compliance checking. If validation is successful, the method will return an object with clean data. If an error is detected, the method calls the brother show_errors () and returns false. Data and errors are stored as class properties. Therefore, they are available for further use, and for the same reason they are cleaned before starting.

The show_errors method inserts error messages next to the form fields, and sets the focus (cursor) to the first field containing the error. So the user can immediately edit the incorrect data, without the need to once again reach for the mouse and click.

The lang method will find the appropriate error message, insert the value from the rule into it, if any, and return a string.

The rule_value method returns the value from the rule. Made in haste, you can probably make much more beautiful through regular expressions. If you have time and understanding - write in the LAN or comments, check and update the code.

The methods min_length, max_length, valid_email, required, min_value, max_value, numeric and alpha_numeric check with the appropriate rules. You can easily add methods.

Here, validation not only checks the data, but also clears them. In this code, the trim and integer methods do this.

The elementary parse_rules method takes a string of rules formatted in the spirit of CodeIgniter and converts it into an array.

The validate_field method, accepts the field name, string and rules for processing, processes the string and checks for compliance with the rules, and then places it in a local data object for later use.

The set_error method simply remembers the error.

Now version of the code with line comments.

 class validation find: (rules, rule) -> #    ,    | rules = rules.split '|' #    -   rule   rules (rule in rules) validate: (rules) -> #       -   .form_error $('.form_error').remove() #    delete @errors_list #        @fields = {} #  ()    @data = {} #      for field, rule of rules #      (  ) @fields[field] = $("input[name=\"#{field}\"]"); #      @data[field] = @fields[field].val() #   @validate_field field, @data[field], rules_string #       unless @errors_list? #   @data else #        @show_errors() #  false false show_errors: -> # ,       focus_set = false #       for field, errors of @errors_list #        messages = [] for error in errors #        messages.push @lang error #       ,     @fields[field].before nano templates.form_error, {message: messages.join(' ')} #     ,       unless focus_set @fields[field].focus() focus_set = true lang: (error) -> #    ,    [rule,value] = @rule_value error if value? #     nano lang.errors[rule], {val: value}) else #    -   ,   lang.errors[rule] rule_value: (rule)-> #    min_length[3] x = rule.split '[' if x[1]? if x[1].substr(x[1].length - 1) == ']' x[1] = x[1].substr 0, x[1].length - 1 [x[0],x[1]] min_length: (str,length) -> #  true,         (str.length >= length) max_length: (str,length) -> #  true,       (str.length < length) valid_email: (str) -> #  true,     (/^[\w\d_-]+@+[\w\d_-]+\.+[\w]/i.test(str)) required: (str) -> #  true,     (@min_length str, 1) min_value: (num,value) -> #  true,     (num > value) max_value: (num,value) -> #  true,     (num < value) numeric: (num) -> #  true,      (/[^\d]/g.test(num)) alpha_numeric: (str) -> #  true,        (/[^\da-z]/gi.test(str)) trim: (str) -> #         str.replace /^\s+|\s+$/g, '' integer: (str) -> #     parseInt(str) parse_rules: (rules) -> #      rules.split '|' validate_field: (field,str,rules) -> #      rules = @parse_rules rules #       for rule_string in rules #    ,    [rule,value] = @rule_value(rule_string) #       result = @[rule] str, value #    - -,  false  true # -   ,    unless result in [true,false] #   str = @data[field] = result #     ,     else unless 'required' not in rules and str.length is 0 if result is no #   @set_error field, rule_string #    ? #   -   , #       CI break set_error: (field,rule) -> #   ,    if @errors_list is undefined @errors_list = {} #      ,     if @errors_list[field] is undefined @errors_list[field] = [] #     @errors_list[field].push rule 


The error messages stored in the object are used, as shown below.

 lang = errors: min_length: ' ,    {val} .' max_length: '  ,   {val} .' min_value: '  ,    {val}.' max_value: '  ,    {val}.' numeric: '  .' alpha_numeric: '     .' valid_email: '     .' required: '   .' 


To handle error messages, the popular minimalistic JS template engine is used, here is its code ported to CoffeeScript

 _nano_regex = /\{([\w\.]*)\}/g nano = (template, data) -> template.replace _nano_regex, (str, key) -> keys = key.split(".") value = data[keys.shift()] $.each keys, -> value = value[this] (if (value is null or value is `undefined`) then "" else value) 


A common task in the framework is to secure quotes.

 add_quotes = (str) -> (if str? then str.replace /"/g, """ else '') 


Using



Suppose there are such fields in the form.

 <label></label> <input type=”text” name=”name” value=””> <label></label> <input type=”text” name=”surname”> <label></label> <input type=”text” name=”email”> 


Then we can set the rules for validation and call processing by submitting the form.

 rules = name: 'trim|required|min_length[2]|max_length[255]' surname: 'trim|max_length[255]' email: 'trim|required|valid_email|max_length[255]' validation = new validation $('body').on 'submit', 'form', => data = validation.validate rules if data isnt off #      else #  .  ,      –            


It turns out minimalistic, flexible and even beautiful code.

Source: https://habr.com/ru/post/184344/


All Articles