Package validator implements value validations for structs and individual fields based on tags. It can also handle Cross-Field and Cross-Struct validation for nested structs and has the ability to dive into arrays and maps of any type. Why not a better error message? Because this library intends for you to handle your own error messages. Why should I handle my own errors? Many reasons. We built an internationalized application and needed to know the field, and what validation failed so we could provide a localized error. Doing things this way is actually the way the standard library does, see the file.Open method here: The authors return type "error" to avoid the issue discussed in the following, where err is always != nil: Validator only returns nil or ValidationErrors as type error; so, in your code all you need to do is check if the error returned is not nil, and if it's not type cast it to type ValidationErrors like so err.(validator.ValidationErrors). Custom functions can be added. Example: Cross-Field Validation can be done via the following tags: If, however, some custom cross-field validation is required, it can be done using a custom validation. Why not just have cross-fields validation tags (i.e. only eqcsfield and not eqfield)? The reason is efficiency. If you want to check a field within the same struct "eqfield" only has to find the field on the same struct (1 level). But, if we used "eqcsfield" it could be multiple levels down. Example: Multiple validators on a field will process in the order defined. Example: Bad Validator definitions are not handled by the library. Example: Baked In Cross-Field validation only compares fields on the same struct. If Cross-Field + Cross-Struct validation is needed you should implement your own custom validator. Comma (",") is the default separator of validation tags. If you wish to have a comma included within the parameter (i.e. excludesall=,) you will need to use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma, so the above will become excludesall=0x2C. Pipe ("|") is the default separator of validation tags. If you wish to have a pipe included within the parameter i.e. excludesall=| you will need to use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe, so the above will become excludesall=0x7C Here is a list of the current built in validators: Tells the validation to skip this struct field; this is particularly handy in ignoring embedded structs from being validated. (Usage: -) This is the 'or' operator allowing multiple validators to be used and accepted. (Usage: rbg|rgba) <-- this would allow either rgb or rgba colors to be accepted. This can also be combined with 'and' for example ( Usage: omitempty,rgb|rgba) When a field that is a nested struct is encountered, and contains this flag any validation on the nested struct will be run, but none of the nested struct fields will be validated. This is usefull if inside of you program you know the struct will be valid, but need to verify it has been assigned. NOTE: only "required" and "omitempty" can be used on a struct itself. Same as structonly tag except that any struct level validations will not run. Is a special tag without a validation function attached. It is used when a field is a Pointer, Interface or Invalid and you wish to validate that it exists. Example: want to ensure a bool exists if you define the bool as a pointer and use exists it will ensure there is a value; couldn't use required as it would fail when the bool was false. exists will fail is the value is a Pointer, Interface or Invalid and is nil. Allows conditional validation, for example if a field is not set with a value (Determined by the "required" validator) then other validation such as min or max won't run, but if a value is set validation will run. This tells the validator to dive into a slice, array or map and validate that level of the slice, array or map with the validation tags that follow. Multidimensional nesting is also supported, each level you wish to dive will require another dive tag. Example #1 Example #2 This validates that the value is not the data types default zero value. For numbers ensures value is not zero. For strings ensures value is not "". For slices, maps, pointers, interfaces, channels and functions ensures the value is not nil. For numbers, max will ensure that the value is equal to the parameter given. For strings, it checks that the string length is exactly that number of characters. For slices, arrays, and maps, validates the number of items. For numbers, max will ensure that the value is less than or equal to the parameter given. For strings, it checks that the string length is at most that number of characters. For slices, arrays, and maps, validates the number of items. For numbers, min will ensure that the value is greater or equal to the parameter given. For strings, it checks that the string length is at least that number of characters. For slices, arrays, and maps, validates the number of items. For strings & numbers, eq will ensure that the value is equal to the parameter given. For slices, arrays, and maps, validates the number of items. For strings & numbers, ne will ensure that the value is not equal to the parameter given. For slices, arrays, and maps, validates the number of items. For numbers, this will ensure that the value is greater than the parameter given. For strings, it checks that the string length is greater than that number of characters. For slices, arrays and maps it validates the number of items. Example #1 Example #2 (time.Time) For time.Time ensures the time value is greater than time.Now.UTC(). Same as 'min' above. Kept both to make terminology with 'len' easier. Example #1 Example #2 (time.Time) For time.Time ensures the time value is greater than or equal to time.Now.UTC(). For numbers, this will ensure that the value is less than the parameter given. For strings, it checks that the string length is less than that number of characters. For slices, arrays, and maps it validates the number of items. Example #1 Example #2 (time.Time) For time.Time ensures the time value is less than time.Now.UTC(). Same as 'max' above. Kept both to make terminology with 'len' easier. Example #1 Example #2 (time.Time) For time.Time ensures the time value is less than or equal to time.Now.UTC(). This will validate the field value against another fields value either within a struct or passed in field. Example #1: Example #2: Field Equals Another Field (relative) This does the same as eqfield except that it validates the field provided relative to the top level struct. This will validate the field value against another fields value either within a struct or passed in field. Examples: Field Does Not Equal Another Field (relative) This does the same as nefield except that it validates the field provided relative to the top level struct. Only valid for Numbers and time.Time types, this will validate the field value against another fields value either within a struct or passed in field. usage examples are for validation of a Start and End date: Example #1: Example #2: This does the same as gtfield except that it validates the field provided relative to the top level struct. Only valid for Numbers and time.Time types, this will validate the field value against another fields value either within a struct or passed in field. usage examples are for validation of a Start and End date: Example #1: Example #2: This does the same as gtefield except that it validates the field provided relative to the top level struct. Only valid for Numbers and time.Time types, this will validate the field value against another fields value either within a struct or passed in field. usage examples are for validation of a Start and End date: Example #1: Example #2: This does the same as ltfield except that it validates the field provided relative to the top level struct. Only valid for Numbers and time.Time types, this will validate the field value against another fields value either within a struct or passed in field. usage examples are for validation of a Start and End date: Example #1: Example #2: This does the same as ltefield except that it validates the field provided relative to the top level struct. This validates that a string value contains alpha characters only This validates that a string value contains alphanumeric characters only This validates that a string value contains a basic numeric value. basic excludes exponents etc... This validates that a string value contains a valid hexadecimal. This validates that a string value contains a valid hex color including hashtag (#) This validates that a string value contains a valid rgb color This validates that a string value contains a valid rgba color This validates that a string value contains a valid hsl color This validates that a string value contains a valid hsla color This validates that a string value contains a valid email This may not conform to all possibilities of any rfc standard, but neither does any email provider accept all posibilities. This validates that a string value contains a valid url This will accept any url the golang request uri accepts but must contain a schema for example http:// or rtmp:// This validates that a string value contains a valid uri This will accept any uri the golang request uri accepts This validates that a string value contains a valid base64 value. Although an empty string is valid base64 this will report an empty string as an error, if you wish to accept an empty string as valid you can use this with the omitempty tag. This validates that a string value contains the substring value. This validates that a string value contains any Unicode code points in the substring value. This validates that a string value contains the supplied rune value. This validates that a string value does not contain the substring value. This validates that a string value does not contain any Unicode code points in the substring value. This validates that a string value does not contain the supplied rune value. This validates that a string value contains a valid isbn10 or isbn13 value. This validates that a string value contains a valid isbn10 value. This validates that a string value contains a valid isbn13 value. This validates that a string value contains a valid UUID. This validates that a string value contains a valid version 3 UUID. This validates that a string value contains a valid version 4 UUID. This validates that a string value contains a valid version 5 UUID. This validates that a string value contains only ASCII characters. NOTE: if the string is blank, this validates as true. This validates that a string value contains only printable ASCII characters. NOTE: if the string is blank, this validates as true. This validates that a string value contains one or more multibyte characters. NOTE: if the string is blank, this validates as true. This validates that a string value contains a valid DataURI. NOTE: this will also validate that the data portion is valid base64 This validates that a string value contains a valid latitude. This validates that a string value contains a valid longitude. This validates that a string value contains a valid U.S. Social Security Number. This validates that a string value contains a valid IP Adress. This validates that a string value contains a valid v4 IP Adress. This validates that a string value contains a valid v6 IP Adress. This validates that a string value contains a valid CIDR Adress. This validates that a string value contains a valid v4 CIDR Adress. This validates that a string value contains a valid v6 CIDR Adress. This validates that a string value contains a valid resolvable TCP Adress. This validates that a string value contains a valid resolvable v4 TCP Adress. This validates that a string value contains a valid resolvable v6 TCP Adress. This validates that a string value contains a valid resolvable UDP Adress. This validates that a string value contains a valid resolvable v4 UDP Adress. This validates that a string value contains a valid resolvable v6 UDP Adress. This validates that a string value contains a valid resolvable IP Adress. This validates that a string value contains a valid resolvable v4 IP Adress. This validates that a string value contains a valid resolvable v6 IP Adress. This validates that a string value contains a valid Unix Adress. This validates that a string value contains a valid MAC Adress. Note: See Go's ParseMAC for accepted formats and types: NOTE: When returning an error, the tag returned in "FieldError" will be the alias tag unless the dive tag is part of the alias. Everything after the dive tag is not reported as the alias tag. Also, the "ActualTag" in the before case will be the actual tag within the alias that failed. Here is a list of the current built in alias tags: Validator notes: This package panics when bad input is provided, this is by design, bad code like that should not make it to production.
text is a repository of text-related packages related to internationalization (i18n) and localization (l10n), such as character encodings, text transformations, and locale-specific text handling.
Package monday is a minimalistic translator for month and day of week names in time.Date objects Monday is not an alternative to standard time package. It is a temporary solution to use while the internationalization features are not ready. That's why monday doesn't create any additional parsing algorithms, layout identifiers. It is just a wrapper for time.Format and time.ParseInLocation and uses all the same layout IDs, constants, etc. Format usage: Parse usage: Monday initializes all its data once in the init func and then uses only func calls and local vars. Thus, it's thread-safe and doesn't need any mutexes to be used with.
Package ctxi18n is used to internationalize applications using the context for the locale.
Package i18n is for app Internationalization and Localization.
Package xconfig loads a configuration file similar to a .ini file, but with some important improvements: - The xconfig recognize bool, int, float and Strings, and also collections of values and hierarchical nested sub-config sets. - The xconfig is compatible with XDataset to inject and use in templates, database records, etc. - You can load more than one file in merge mode or replacing mode in the same config object. - You can set and get parameters at any time. - You can load the config object based on a file, but also on a string and another object; this way you can serialize, unserialize, transfer by any strem, save or load on database the object, etc. - You can also save back the config string with all its comments. 1. Installing the package: Execute on your operating system: 2. Importing the package: 3. Then you need first to create a blank XConfig instance: 4. Then, you generally load a file to fill in your XConfig definition 5. Use the configuration myparam will take the type of the parameter: string, integer, float64, bool, or an array of string, integer or float64. (you should be aware of the type of your parameter before using it). You can also use the Get* cast functions. 6. You can also set some new parameters 7. And finally save the new configuration The config file is a simple utf8 flat text file. The configuration file is a set of key=value parameters, with optional comments. The configuration file have the following syntax: You can add as many as parameters you wish into the file. 1. comments: You may add comments and also comment unused parameter with # or ; at the beginning of the line 2. Parameter keys: The parameter key is a string with characters [a-zA-Z0-9_-] only, with a minimum of 1 character. The point (.) denotes a sub set of parameters (a new sub XConfig dataset for this parameter) In this case the database entry of the XConfig is again another XConfig with 3 parameters into it: user, pass and db. 3. Assignation sign: A simple = sign is the normal assignation, the "add" or "replace" behaviour depends on the funcion called for loading the configuration (Load* or Merge* functions). In this case various asignation to the same parameter will create an array of values of the same type as the first declared parameter. An equal sign preceded by a + (+=) will always add the parameter to the array of values, never replace it (see Merge/Load). An equal sign preceded by a : (:=) will always replace the parameter and discard any already set values. 4. Parameter values: There are 4 types of values: - Strings - Integer - Float - Boolean The value has no restrictions except it must enter into the line (no line breaks allowed) The compiler accepts strings "true", "on", "yes" as a boolean 'true' and "false", "off", "no", "none" as a boolean 'false'. For instance, that means parameter=off is a boolean false, and parameter=yes is a boolean true in the XConfig structure. The compiler also convert all integers to an int parameter in the XConfig structure, and float values as float64 type. If you want a natural integer, float or boolean interpreted as a string, you must start it with a " character: param1="123 will be the string 123 in the XConfig structure If you want a string starting with a ", you will need to put 2 " at the beginning: param=""abc will be the string "abc in the XConfig structure 3. list of values: You can repeat as many time you need the same parameter name with different values. This will build a list of values in the object. The list of values is kept as an array of values. If you have a mixed type of values, you will get an error. for instance: The order IS important. Once loaded you will get a []string{“es”, “en”, “fr”, “jp”} assigned to the “languages” parameter. + and : You may load two config file (or more), for example when you have a master config file and a local replacement values config file. In this case, the values of the second file will "replace" the data already loaded with the first file. This is a replacement of config entries. In the other hand, you may merge two config files (or more), for example when you need to fragment the data into a set of simpler files. In this case, the values will just be "added" as if the two files were a simple file (create arrays on same id entries). This is a merging of config entries. If you want to force the behaviour of variables (merging into a replacement loading, or replace into a merging loading), you may use the two assignement operators + and : := will be used to replace a value by a new value, meanwhile += will be used to add a new value to the array of data. The rules of "same type of data" must be observed also in this case (+=) With the following files: The result config after merging local into global will be: The XConfig object is easily usable as: or, if you load your own file by other means (remote, database etc) or, if you already have your configuration into a Map of Strings (unserialized, etc) There are 3 sets of public functions: Load*: to load a file, a string dataset, or another XConfig dataset. Loading means all already existing parameters will be replaced by the new configuration. This is useful when you have a main config file, and a local config file that must replace some values Functions are LoadFile, LoadString and LoadXConfig Merge*: to merge a file, a string dataset, or another XConfig dataset. Merging means all new entries will be added to the already existing parameters. This is userfull then you split your config file into subset of parameters each (for instance database config, memory config, internationalization config, etc) Functions are MergeFile, MergeString and MergeXConfig Get/Set/Add: to read, set (replace) or add (merge) parameters to the XConfig. Once you have an instance of your configuration, you may use it like this: After loading, creating, modifying your configuration file, you may need to save your configuration. For this yoy have 2 functions: Note: if you load your configuration file with comments in it, when you save it, the comments and presentation (new lines) will be respected. If you add new parameters, they will be added to the end of the file. New lines will be removed into the definition of an array of data.
text is a repository of text-related packages related to internationalization (i18n) and localization (l10n), such as character encodings, text transformations, and locale-specific text handling. There is a 30 minute video, recorded on 2017-11-30, on the "State of golang.org/x/text" at https://www.youtube.com/watch?v=uYrDrMEGu58
Package ldapstrprep implements string preparation algorithms described in RFC 4518 (Lightweight Directory Access Protocol Internationalized String Preparation), including errata (as of 2020-09) Relations between RFC 4518 six-step process and functions are following: 1) Transcode: Note: To transcode non-Unicode string value to string, such as ut8string to string, is out of this function's scope. Use asn.1 or another package. 2) Map: 3) Normalize 4) Prohibit 5) Check bidi 6) Insignificant Character Handling 6-1) Insignificant Space Handling 6-1-1) For attribute values or non-substring assertion values: 6-1-2) For substring assertion values: 6-1-2-1) For Initial 6-1-2-2) For Final 6-1-2-3) For Any 6-2) numericString Insignificant Character Handling: 6-3) telephoneNumber Insignificant Character Handling:
Package curie implements the type for compact URI. It defines a generic syntax for expressing URIs by abbreviated literal as defined by the W3C. https://www.w3.org/TR/2010/NOTE-curie-20101216/ Package curie The type `curie` ("Compact URI") defines a generic syntax for expressing URIs by abbreviated literal as defined by the W3C. https://www.w3.org/TR/2010/NOTE-curie-20101216/. The type supports type safe domain driven design using aspects of hierarchical linked-data. Linked-Data are used widely by Semantic Web to publish structured data so that it can be interlinked by applications. Internationalized Resource Identifiers (IRIs) are key elements to cross-link data structure and establish references (pointers) to data elements. These IRIs may be written as relative, absolute or compact IRIs. The `curie` type is just a formal definition of compact IRI (superset of XML QNames). Another challenge solved by `curie` is a formal mechanism to permit the use of hierarchical extensible name collections and its serialization. All-in-all CURIEs expand to any IRI. Compact URI is superset of XML QNames. It is comprised of two components: a prefix and a suffix, separated by `:`. Omit prefix to declare a relative URI; omit suffix to declare namespace only; omit both components to declare empty URI. See W3C CURIE Syntax 1.0 https://www.w3.org/TR/2010/NOTE-curie-20101216/ ↣ zero: empty compact URI ↣ transform: string ⟼ CURIE ↣ binary compose: CURIE × CURIE ⟼ CURIE ↣ unary decompose: CURIE ⟼ CURIE ↣ rank: |CURIE| ⟼ Int ↣ binary ordering: CURIE ≼ CURIE ⟼ bool Cross-linking of structured data is an essential part of type safe domain driven design. The library helps developers to model relations between data instances using familiar data type: `curie.ID` and `curie.IRI` are sibling, equivalent CURIE data type. `ID` is only used as primary key, `IRI` is a "pointer" to linked-data. CURIE type is core type to organize hierarchies. An application declares `A ⟼ B` hierarchical relation using path at suffix. For example, the root is `curie.New("some:a")`, 2nd rank node `curie.New("some:a/b")` and so on `curie.New("some:a/b/c/e/f")`.
Package norm contains middleware for normalizing forms in HTTP requests. In particular this package is useful for normalizing forms submitted with HTTP requests using the PRECIS (preparation, enforcement, and comparison of internationalized strings) security framework. Custom normalization rules may also be applied eg. to normalize using the legacy STRINGPREP algorithm or perform other validations.
Package i18n is internationalization and localization support for aah framework. Messages config format is `forge` config syntax (go-aah/config) which is similar to HOCON syntax aka typesafe config. Message filename format is `message.<Language-ID>`. Language ID is combination of `Language + Region` or `Language` value. aah framework implements Language code is as per two-letter `ISO 639-1` standard and Region code is as per two-letter `ISO 3166-1` standard. Supported message file extension formats are (incasesensitive) Language + Region => en-us | en-US Language => en For Example: message.en-US or message.en-us message.en-GB or message.en-gb message.en-CA or message.en-ca message.en message.es message.zh message.nl etc. Note: Sub directories is supported, so you can organize message files.
This is a GSSAPI provider for Go, which expects to be initialized with the name of a dynamically loadable module which can be dlopen'd to get at a C language binding GSSAPI library. The GSSAPI concepts are explained in RFC 2743, "Generic Security Service Application Program Interface Version 2, Update 1". The API calls for C, together with a number of values for constants, come from RFC 2744, "Generic Security Service API Version 2 : C-bindings". Note that the basic GSSAPI bindings for C use the Latin-1 character set. UTF-8 interfaces are specified in RFC 5178, "Generic Security Service Application Program Interface (GSS-API) Internationalization and Domain-Based Service Names and Name Type", in 2008. Looking in 2013, this API does not appear to be provided by either MIT or Heimdal. This API applies solely to hostnames though, which can also be supplied in ACE encoding, bypassing the issue. For now, we assume that hostnames and usercodes are all ASCII-ish and pass UTF-8 into the library. Patches for more comprehensive support welcome.
Package i18n offers the following basic internationalization functionality: There's more we'd like to add in the future, including: In order to interact with this package, you must first get a TranslatorFactory instace. Through the TranslatorFactory, you can get a Translator instance. Almost everything in this package is accessed through methods on the Translator struct. About the rules and messages paths: This package ships with built-in rules, and you are welcome to use those directly. However, if there are locales or rules that are missing from what ships directly with this package, or if you desire to use different rules than those that ship with this package, then you can specify additional rules paths. At this time, this package does not ship with built-in messages, other than a few used for the unit tests. You will need to specify your own messages path(s). For both rules and messages paths, you can specify multiple. Paths later in the slice take precedence over packages earlier in the slice. For a basic example of getting a TranslatorFactory instance: For simple message translation, use the Translate function, and send an empty map as the second argument (we'll explain that argument in the next section). You can also pass placeholder values to the translate function. That's what the second argument is for. In this example, we will inject a username into the translation. You can also translate strings with plurals. However, any one message can contain at most one plural. If you want to translate "I need 5 apples and 3 oranges" you are out of luck. The Pluralize method takes 3 arguments. The first is the message key - just like the Translate method. The second argument is a float which is used to determine which plural form to use. The third is a string representation of the number. Why two arguments for the number instead of one? This allows you ultimate flexibility in number formatting to use in the translation while eliminating the need for string number parsing. You can use the "FomatNumber", "FormatCurrency" and "FormatPercent" methods to do locale-based number formatting for numbers, currencies and percentages. If you need to sort a list of strings alphabetically, then you should not use a simple string comparison to do so - this will often result in incorrect results. "ȧ" would normally evaluate as greater than "z", which is not correct in any latin writing system alphabet. Use can use the Sort method on the Translator struct to do an alphabetic sorting that is correct for that locale. Alternatively, you can access the SortUniversal and the SortLocale functions directly without a Translator instance. SortUniversal does not take a specific locale into account when doing the alphabetic sorting, which means it might be slightly less accurate than the SortLocal function. However, there are cases in which the collation rules for a specific locale are unknown, or the sorting needs to be done in a local-agnostic way. For these cases, the SortUniversal function performs a unicode normalization in order to best sort the strings. In order to be flexible, these functions take a generic interface slice and a function for retrieving the value on which to perform the sorting. For example: When getting a Translator instance, the TranslatorFactory will automatically attempt to determine an appropriate fallback Translator for the locale you specify. For locales with specific "flavors", like "en-au" or "zh-hans", the "vanilla" version of that locale will be used if it exists. In these cases that would be "en" and "zh". When creating a TranslatorFactory instance, you can optionally specify a final fallback locale. This will be used if it exists. When determining a fallback, the the factory first checks the less specific versions of the specified locale, if they exist and will ultimate fallback to the global fallback if specified. All of the examples above conveniently ignore errors. We recommend that you DO handle errors. The system is designed to give you a valid result if at all possible, even in errors occur in the process. However, the errors are still returned and may provide you helpful information you might otherwise miss - like missing files, file permissions problems, yaml format problems, missing translations, etc. We recommend that you do some sort of logging of these errors.
Package i18n provides internationalization utilities.
text is a repository of text-related packages related to internationalization (i18n) and localization (l10n), such as character encodings, text transformations, and locale-specific text handling.
text is a repository of text-related packages related to internationalization (i18n) and localization (l10n), such as character encodings, text transformations, and locale-specific text handling. There is a 30 minute video, recorded on 2017-11-30, on the "State of github.com/Andyfoo/golang/x/text" at https://www.youtube.com/watch?v=uYrDrMEGu58
Package monday is a minimalistic translator for month and day of week names in time.Date objects Monday is not an alternative to standard time package. It is a temporary solution to use while the internationalization features are not ready. That's why monday doesn't create any additional parsing algorithms, layout identifiers. It is just a wrapper for time.Format and time.ParseInLocation and uses all the same layout IDs, constants, etc. Format usage: Parse usage: Monday initializes all its data once in the init func and then uses only func calls and local vars. Thus, it's thread-safe and doesn't need any mutexes to be used with.
text is a repository of text-related packages related to internationalization (i18n) and localization (l10n), such as character encodings, text transformations, and locale-specific text handling.
Package monday is a minimalistic translator for month and day of week names in time.Date objects Monday is not an alternative to standard time package. It is a temporary solution to use while the internationalization features are not ready. That's why monday doesn't create any additional parsing algorithms, layout identifiers. It is just a wrapper for time.Format and time.ParseInLocation and uses all the same layout IDs, constants, etc. Format usage: Parse usage: Monday initializes all its data once in the init func and then uses only func calls and local vars. Thus, it's thread-safe and doesn't need any mutexes to be used with.
text is a repository of text-related packages related to internationalization (i18n) and localization (l10n), such as character encodings, text transformations, and locale-specific text handling.