Error message for string length

The default ErrorMessage for StringLength validation is a lot longer than I'd like: The field {Name} must be a string with a maximum length of {StringLength}. I would like to change it universa...

You can specify the StringLength attribute as follows on numerous properties

[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string OfficePhone { get; set; }
[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string CellPhone { get; set; }

and add the string resource (named StringLengthMessage) in your resource file

"Maximum length is {1}"

Message is defined once and has a variable place holder should you change your mind regarding the length to test against.

You can specify the following:

  1. {0} — Name
  2. {1} — Maximum Length
  3. {2} — Minimum Length

Update

To minimize duplication even further you can subclass StringLengthAttribute:

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute() : this(20)
    {
    }

    public MyStringLengthAttribute(int maximumLength) : base(maximumLength)
    {
        base.ErrorMessageResourceName = "StringLengthMessage";
        base.ErrorMessageResourceType = typeof (Resource);
    }
}

Or you can override FormatErrorMessage if you want to add additional parameters. Now the properties look as follows:

[MyStringLength]
public string OfficePhone { get; set; }
[MyStringLength]
public string CellPhone { get; set; }

In the MVC4 template one of the data annotation attributes used is stringlength.

For example:

[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]

What parameters {0}, {1}, {2} (more?) are legal?

Edit: To be more specific, I can see from the example and trial and error what the possibilities are, but I would like to see some hard documentation.

I can’t find anything about this in the StringLengthAttribute documentation.

asked Nov 16, 2012 at 22:23

Anders E. Andersen's user avatar

The {0} index is the display name of property, {1} is the MaximumLength, {2} is the MinimumLength. So, your error message will be formate as "The Foo must be at least 6 characters long."

answered Nov 16, 2012 at 22:26

Sergey Berezovskiy's user avatar

3

I haven’t seen any documentation either, but the FormatErrorMessage method for the StringLengthAttribute looks like this:

public override string FormatErrorMessage(string name)
{
    EnsureLegalLengths();
    string format = ((this.MinimumLength != 0) && !base.CustomErrorMessageSet) ? DataAnnotationsResources.StringLengthAttribute_ValidationErrorIncludingMinimum : base.ErrorMessageString;
    return String.Format(CultureInfo.CurrentCulture, format, new object[] { name, MaximumLength, MinimumLength });
}

answered Dec 17, 2013 at 11:07

Oundless's user avatar

OundlessOundless

5,3654 gold badges30 silver badges32 bronze badges

A longer-than-expected Google search brought me to this old topic before I could start getting some solid leads, so I’ll put this here and hope it helps anyone else in the same shoes:

Inspecting the code for StringLengthAttribute that MS put up on GitHub confirms the logic residing in the FormatErrorMessage method:

// it's ok to pass in the minLength even for the error message without a {2} param since String.Format will just
// ignore extra arguments
return String.Format(CultureInfo.CurrentCulture, errorMessage, name, this.MaximumLength, this.MinimumLength);

Thus ‘0’, ‘1’, and ‘2’ corresponds to ‘name’ (of Property), ‘MaximumLength’, and ‘MinimumLength’ accordingly.

I bet the same method can be applied to all other validation attributes to check their formatting parameters accordingly; I was not able to find any other documentation for this infomation otherwise.

answered Aug 15, 2018 at 8:52

Bo Ngoh's user avatar

Bo NgohBo Ngoh

1331 silver badge8 bronze badges

1

  • Remove From My Forums
  • Question

  • User-777524703 posted

    Hello,

    I’m trying to figure out the format of StringLengthAttribute.ErrorMessage. What are the parameters passed when formatting this string? Let’s say I want to show a message like this (for password validation):

    [StringLength(100, ErrorMessage = «The password must be at least {0} characters», MinimumLength = 6)]

    Would it format correctly? Here’s an example I don’t understand:

    http://mvcmusicstore.codeplex.com/SourceControl/changeset/view/d9f25c5263ed#MvcMusicStore%2fModels%2fAccountModels.cs

    It looks like this:

    [Required]
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "New password")]
            public string NewPassword { get; set; }
    What is {0} and {1}? Where do I read up on this information?

    /Daniel

Answers

  • User1904378495 posted

    You can find the full documentation here

    http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute.aspx

    [StringLength(100, ErrorMessage = «The password must be at least {0} characters», MinimumLength = 6)]

    In this case error message is just a string template that is applied when rendered. Think of a string.Format. So it is equivalent to 

    string.Format(«The {0} must be at least {2} characters long.»,DisplayName,MaximumLength,MinimumLength);

    The 0 index is the display name of the property, 1 is the maximum length, 2 is the minimum length

    For your example, this would show the display name instead of the minimum length. You need to change {0} to {2}

    [StringLength(100, ErrorMessage = «The password must be at least {0} characters», MinimumLength = 6)] 

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Вы можете указать атрибут StringLength следующим образом во многих свойствах.

[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string OfficePhone { get; set; }
[StringLength(20, ErrorMessageResourceName = "StringLengthMessage", ErrorMessageResourceType = typeof(Resource))]
public string CellPhone { get; set; }

и добавьте строковый ресурс (названный StringLengthMessage) в вашем файле ресурсов

"Maximum length is {1}"

Сообщение определяется один раз и имеет переменный заполнитель, если вы передумаете относительно длины для проверки.

Вы можете указать следующее:

  1. {0} — Имя
  2. {1} — длина максимальная
  3. {2} — Минимальная длина

Обновить

Чтобы минимизировать дублирование еще больше, вы можете создать подкласс StringLengthAttribute:

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute() : this(20)
    {
    }

    public MyStringLengthAttribute(int maximumLength) : base(maximumLength)
    {
        base.ErrorMessageResourceName = "StringLengthMessage";
        base.ErrorMessageResourceType = typeof (Resource);
    }
}

Или вы можете переопределить FormatErrorMessage если вы хотите добавить дополнительные параметры. Теперь свойства выглядят следующим образом:

[MyStringLength]
public string OfficePhone { get; set; }
[MyStringLength]
public string CellPhone { get; set; }

A validation rule that demands the target value length be within the specified value range (including the range’s end points).

To specify the range that the validated value length must match, set the rule’s min and max configuration properties.

This rule validates string values or the values that can be cast to a string.

View Demo

See Also
  • Data Validation

If set to true, empty values are valid.

Specifies the maximum length allowed for the validated value.

Specifies the message that is shown if the rule is broken.

Default Value: ‘The length of the value is not correct’

An error message can be specified as follows:

  • Hard-code the message

    jQuery

    index.js

    $(function() {
        $("#textBox").dxTextBox({ ... })
            .dxValidator({
                type: "stringLength",
                message: "My custom message"
            });
    });
    Angular

    app.component.html

    app.module.ts

    <dx-text-box> 
        <dx-validator>
            <dxi-validation-rule 
                type="stringLength" 
                message="My custom message">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    
    import { DxValidatorModule,
             DxTextBoxModule } from 'devextreme-angular';
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            DxTextBoxModule,
            BrowserModule,
            DxValidatorModule
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    Vue

    App.vue

    <template>
        <DxTextBox>
            <DxValidator>
                <DxStringLengthRule
                    message="My custom message"
                />
            </DxValidator>
        </DxTextBox>
    </template>
    
    <script>
    import 'devextreme/dist/css/dx.light.css';
    
    import { DxTextBox } from 'devextreme-vue/text-box';
    import {
        DxValidator,
        DxStringLengthRule
    } from 'devextreme-vue/validator';
    
    export default {
        components: {
            DxTextBox,
            DxValidator,
            DxStringLengthRule
        }
    }
    </script>
    React

    App.js

    import React from 'react';
    
    import 'devextreme/dist/css/dx.light.css';
    
    import { TextBox } from 'devextreme-react/text-box';
    import {
        Validator,
        StringLengthRule
    } from 'devextreme-react/validator';
    
    class App extends React.Component {
        render() {
            return (
                <TextBox>
                    <Validator>
                        <StringLengthRule
                            message="My custom message" />
                    </Validator>
                </TextBox>
            );
        }
    }
    export default App;
  • Hide the message

    jQuery

    index.js

    $(function() {
        $("#textBox").dxTextBox({ ... })
            .dxValidator({
                type: "stringLength",
                message: ""
            });
    });
    Angular

    app.component.html

    app.module.ts

    <dx-text-box>
        <dx-validator>
            <dxi-validation-rule 
                type="stringLength" 
                message="">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    
     import { DxValidatorModule,
              DxTextBoxModule } from 'devextreme-angular';
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule,
            DxValidatorModule,
            DxTextBoxModule
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    Vue

    App.vue

    <template>
        <DxTextBox>
            <DxValidator>
                <DxStringLengthRule
                    message=""
                />
            </DxValidator>
        </DxTextBox>
    </template>
    
    <script>
    import 'devextreme/dist/css/dx.light.css';
    
    import { DxTextBox } from 'devextreme-vue/text-box';
    import {
        DxValidator,
        DxStringLengthRule
    } from 'devextreme-vue/validator';
    
    export default {
        components: {
            DxTextBox,
            DxValidator,
            DxStringLengthRule
        }
    }
    </script>
    React

    App.js

    import React from 'react';
    
    import 'devextreme/dist/css/dx.light.css';
    
    import { TextBox } from 'devextreme-react/text-box';
    import {
        Validator,
        StringLengthRule
    } from 'devextreme-react/validator';
    
    class App extends React.Component {
        render() {
            return (
                <TextBox>
                    <Validator>
                        <StringLengthRule
                            message="" />
                    </Validator>
                </TextBox>
            );
        }
    }
    export default App;
  • Display the editor’s name in the message

    jQuery

    index.js

    $(function() {
        $("#textBox").dxTextBox({ ... })
            .dxValidator({
                name: "password", // The error message will be "The length of the password is not correct"
                validationRules: [{
                    type: "stringLength"
                }]
            });
    });
    Angular

    app.component.html

    app.module.ts

    <dx-text-box>
        <!-- The error message will be "The length of the password is not correct" -->
        <dx-validator name="password">
            <dxi-validation-rule 
                type="stringLength">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    
    import { DxValidatorModule,
             DxTextBoxModule } from 'devextreme-angular';
    
    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule,
            DxValidatorModule,
            DxTextBoxModule
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    Vue

    App.vue

    <template>
        <DxTextBox>
            <!-- The error message will be "The length of the password is not correct" -->
            <DxValidator name="password">
                <DxStringLengthRule />
            </DxValidator>
        </DxTextBox>
    </template>
    
    <script>
    import 'devextreme/dist/css/dx.light.css';
    
    import { DxTextBox } from 'devextreme-vue/text-box';
    import {
        DxValidator,
        DxStringLengthRule
    } from 'devextreme-vue/validator';
    
    export default {
        components: {
            DxValidator,
            DxStringLengthRule
        }
    }
    </script>
    React

    App.js

    import React from 'react';
    
    import 'devextreme/dist/css/dx.light.css';
    
    import { TextBox } from 'devextreme-react/text-box';
    import {
        Validator,
        StringLengthRule
    } from 'devextreme-react/validator';
    
    class App extends React.Component {
        render() {
            return (
                <TextBox>
                    {/* The error message will be "The length of the password is not correct" */}
                    <Validator name="password">
                        <StringLengthRule} />
                    </Validator>
                </TextBox>
            );
        }
    }
    
    export default App;

Specifies the minimum length allowed for the validated value.

Indicates whether or not to remove the Space characters from the validated value.

To keep the Space characters within the validated value, set this field to false.

Specifies the rule type. Set it to «stringLength» to use the StringLengthRule.

Accepted Values: ‘required’ | ‘numeric’ | ‘range’ | ‘stringLength’ | ‘custom’ | ‘compare’ | ‘pattern’ | ’email’ | ‘async’

Was this topic helpful?

Thank you!

Feel free to share demo-related thoughts here.
If you have technical questions, please create a support ticket in the DevExpress Support Center.

Thank you!
We appreciate your feedback.

This is a low level tex parse error the wording comes from tex-the-program, traditionally it would have been visible in the pool file, but modern implementations do not use a separate pool file).

As such it can not be changed from tex code, all you could do is modify (say) setlength to detect non-length input and avoid attempting a primitive length assignment.


For luatex you can do this:

documentclass{article}

directlua{
function my_error ()
local e =status.lasterrorstring
if(e=='! Missing number, treated as zero') then
  texio.write_nl ('! Missing number,stringnspacespace perhaps you should look at page 6')
else if(e=='! Illegal unit of measure (pt inserted)') then
  texio.write_nl ('! Illegal unit of measurestringnspacespace you really should look at page 6 of the documentaion')
else
  texio.write_nl(e)
end
end
end
luatexbase.add_to_callback('show_error_message',my_error,'error message hook')
}
begin{document}

setlengthoddsidemargin{x}

newcommandcos{sin}

def  x {y}

end{document}

which produces a terminal output of:

! Missing number,
  perhaps you should look at page 6.
<to be read again> 
x
l.19 setlengthoddsidemargin{x}

? 
! Illegal unit of measure
  you really should look at page 6 of the documentaion.
<to be read again> 
x
l.19 setlengthoddsidemargin{x}

? 

! LaTeX Error: Command cos already defined.
               Or name end... illegal, see p.192 of the manual.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                              

l.21 newcommandcos{sin}

? 

Понравилась статья? Поделить с друзьями:
  • Error message file too big перевод
  • Error message file specification fl studio
  • Error message file access denied
  • Error message end of script output before headers
  • Error message design