Blazor playground

Nova v3.37.0

Preview

Blazor

Fieldtextarea

← nv-fieldtextarea

NvFieldtextarea Component - Practical Guide for Blazor Developers

The NvFieldtextarea component is a Blazor wrapper around Nova's textarea input component, providing seamless integration with Blazor's data binding, forms, and validation systems.

General Blazor Concepts

For general information about data binding, forms, and validation in Nova Blazor components, see the Nova Blazor Integration Guide. This guide focuses on textarea-specific features and patterns.

Basic Usage

Simple Textarea

razor<NvFieldtextarea Label="Comments" Placeholder="Enter your comments here..." />

Textarea with Description

razor<NvFieldtextarea
    Label="Feedback"
    Description="Please provide detailed feedback about your experience"
    Rows="4"
    Placeholder="Tell us what you think..." />

Data Binding

The component supports Blazor's @bind-Value syntax for two-way data binding:

razor<NvFieldtextarea @bind-Value="comments"
                 Label="Comments"
                 Rows="4"
                 Placeholder="Enter your comments..." />

@code {
    private string comments = "";
}

For more information on data binding and event handling, see the Nova Blazor Integration Guide.

Textarea-Specific Features

Autosize and Resize Options

Autosize Textarea

razor<NvFieldtextarea
    @bind-Value="message"
    Label="Auto-resizing Message"
    Autosize="true"
    Placeholder="This textarea will grow as you type..." />

Resize Control

razor<NvFieldtextarea
    @bind-Value="code"
    Label="Code Editor"
    Rows="10"
    Resize="ResizeEnum.both"
    Placeholder="Write your code here..." />

<NvFieldtextarea
    @bind-Value="notes"
    Label="Notes (Vertical Only)"
    Rows="4"
    Resize="ResizeEnum.vertical"
    Placeholder="Notes that can only resize vertically..." />

<NvFieldtextarea
    @bind-Value="title"
    Label="Title (Fixed Size)"
    Rows="2"
    Resize="ResizeEnum.none"
    Placeholder="Fixed size textarea..." />

Form Integration and Validation

Textareas work seamlessly with Blazor's EditForm and validation:\n\n```razor

plaintext<NvFieldtextarea @bind-Value="model.Comments"
                 Label="Comments"
                 Rows="4"
                 Required="true"
                 Maxlength="500"
                 For="@(() => model.Comments)" />

<button type="submit">Submit</button>

@code { private Model model = new();

plaintextpublic class Model
{
    [Required]
    [StringLength(500)]
    public string? Comments { get; set; }
}

}

plaintext
For detailed information on forms and validation, see the [Nova Blazor Integration Guide](../../../../../Nova/README.md).

## Textarea-Specific Patterns

### Required Field Validation

```razor
<EditForm Model="contactModel" OnValidSubmit="SendMessage">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="contactModel.Name"
        Label="Your Name"
        For="() => contactModel.Name" />

    <NvFieldtextarea
        @bind-Value="contactModel.Message"
        Label="Message"
        Required="true"
        Rows="5"
        For="() => contactModel.Message" />

    <button type="submit">Send Message</button>
</EditForm>

@code {
    private ContactModel contactModel = new();

    public class ContactModel
    {
        [Required]
        public string? Name { get; set; }

        [Required(ErrorMessage = "Please enter your message")]
        [MinLength(10, ErrorMessage = "Message must be at least 10 characters long")]
        public string? Message { get; set; }
    }
}

Length Validation

razor<EditForm Model="postModel" OnValidSubmit="CreatePost">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="postModel.Title"
        Label="Post Title"
        For="() => postModel.Title" />

    <NvFieldtextarea
        @bind-Value="postModel.Content"
        Label="Post Content"
        Rows="8"
        Maxlength="2000"
        Description="Maximum 2000 characters"
        For="() => postModel.Content" />

    <NvFieldtextarea
        @bind-Value="postModel.Summary"
        Label="Summary"
        Rows="3"
        Maxlength="300"
        Description="Brief summary (max 300 characters)"
        For="() => postModel.Summary" />

    <button type="submit">Create Post</button>
</EditForm>

@code {
    private PostModel postModel = new();

    public class PostModel
    {
        [Required]
        [StringLength(100, ErrorMessage = "Title cannot exceed 100 characters")]
        public string? Title { get; set; }

        [Required]
        [StringLength(2000, ErrorMessage = "Content cannot exceed 2000 characters")]
        public string? Content { get; set; }

        [StringLength(300, ErrorMessage = "Summary cannot exceed 300 characters")]
        public string? Summary { get; set; }
    }
}

Custom Validation

razor<EditForm Model="reviewModel" OnValidSubmit="SubmitReview">
    <DataAnnotationsValidator />

    <NvFieldtextarea
        @bind-Value="reviewModel.ReviewText"
        Label="Your Review"
        Rows="6"
        For="() => reviewModel.ReviewText" />

    <button type="submit">Submit Review</button>
</EditForm>

@code {
    private ReviewModel reviewModel = new();

    public class ReviewModel
    {
        [Required]
        [CustomReviewValidation]
        public string? ReviewText { get; set; }
    }

    public class CustomReviewValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            var text = value as string;
            if (string.IsNullOrWhiteSpace(text))
                return new ValidationResult("Review text is required");

            if (text.Length < 20)
                return new ValidationResult("Review must be at least 20 characters long");

            if (text.Length > 1000)
                return new ValidationResult("Review cannot exceed 1000 characters");

            // Check for minimum word count
            var words = text.Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
            if (words.Length < 5)
                return new ValidationResult("Review must contain at least 5 words");

            return ValidationResult.Success;
        }
    }
}

Advanced Scenarios

Character Counter with Validation

razor<NvFieldtextarea
    @bind-Value="message"
    Label="Message"
    Rows="4"
    Maxlength="500"
    ValueChanged="UpdateCharacterCount"
    Description="@characterCountText" />

@code {
    private string message = "";
    private string characterCountText = "0 / 500 characters";

    private void UpdateCharacterCount(string value)
    {
        message = value;
        var count = value?.Length ?? 0;
        characterCountText = $"{count} / 500 characters";

        if (count > 450)
        {
            characterCountText += " (approaching limit)";
        }
        else if (count > 500)
        {
            characterCountText += " (over limit!)";
        }
    }
}

Auto-save with Debouncing

razor<NvFieldtextarea
    @bind-Value="documentContent"
    Label="Document Content"
    Rows="10"
    Autosize="true"
    ValueChanged="OnContentChanged"
    Placeholder="Start writing your document..." />

@if (isSaving)
{
    <span>Saving...</span>
}
else if (lastSaved.HasValue)
{
    <span>Last saved: @lastSaved.Value.ToString("HH:mm:ss")</span>
}

@code {
    private string documentContent = "";
    private bool isSaving = false;
    private DateTime? lastSaved;
    private CancellationTokenSource? _debounceCts;

    private async Task OnContentChanged(string value)
    {
        documentContent = value;

        // Cancel previous save operation
        _debounceCts?.Cancel();
        _debounceCts = new CancellationTokenSource();

        try
        {
            // Wait 2 seconds before auto-saving
            await Task.Delay(2000, _debounceCts.Token);
            await AutoSaveDocument(value);
        }
        catch (TaskCanceledException)
        {
            // Save was cancelled due to new changes, ignore
        }
    }

    private async Task AutoSaveDocument(string content)
    {
        isSaving = true;
        try
        {
            // Simulate API call
            await Task.Delay(1000);
            lastSaved = DateTime.Now;
        }
        finally
        {
            isSaving = false;
        }
    }
}

Collaborative Editing Simulation

razor<NvFieldtextarea
    @bind-Value="sharedDocument"
    Label="Shared Document"
    Rows="8"
    Autosize="true"
    ValueChanged="OnDocumentChanged"
    Placeholder="Start collaborating..." />

<div class="collaborators">
    @foreach (var change in recentChanges)
    {
        <div class="change">@change</div>
    }
</div>

@code {
    private string sharedDocument = "";
    private List<string> recentChanges = new();

    private void OnDocumentChanged(string value)
    {
        sharedDocument = value;

        // Simulate collaborative editing
        var change = $"Content updated at {DateTime.Now.ToString("HH:mm:ss")}";
        recentChanges.Insert(0, change);

        // Keep only last 5 changes
        if (recentChanges.Count > 5)
        {
            recentChanges = recentChanges.Take(5).ToList();
        }
    }
}

Markdown Preview

razor<div class="editor-container">
    <div class="editor-section">
        <NvFieldtextarea
            @bind-Value="markdownContent"
            Label="Markdown Content"
            Rows="10"
            Autosize="true"
            ValueChanged="UpdatePreview"
            Placeholder="Write in Markdown..." />
    </div>

    <div class="preview-section">
        <h4>Preview</h4>
        <div class="markdown-preview">
            @((MarkupString)renderedHtml)
        </div>
    </div>
</div>

@code {
    private string markdownContent = "";
    private string renderedHtml = "";

    private void UpdatePreview(string value)
    {
        markdownContent = value;
        // Simple markdown-like rendering (in real app, use a proper markdown parser)
        renderedHtml = value
            .Replace("\n", "<br>")
            .Replace("**", "<strong>", StringComparison.Ordinal)
            .Replace("**", "</strong>", StringComparison.Ordinal)
            .Replace("*", "<em>", StringComparison.Ordinal)
            .Replace("*", "</em>", StringComparison.Ordinal);
    }
}

Best Practices

  1. Set appropriate row counts for expected content length
  2. Use autosize for dynamic content to improve UX
  3. Control resize behavior based on use case (none for fixed layouts, vertical for most forms)
  4. Always provide clear labels for accessibility
  5. Use descriptions to guide users on content expectations
  6. Implement character limits for constrained inputs
  7. Consider debouncing for real-time features like auto-save
  8. Handle long content appropriately with scrolling or pagination

Common Patterns

Contact Form

razor<EditForm Model="contactForm" OnValidSubmit="SendContactForm">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="contactForm.Name"
        Label="Full Name"
        For="() => contactForm.Name" />

    <NvFieldtext
        @bind-Value="contactForm.Email"
        Label="Email Address"
        Type="TypeEnum.email"
        For="() => contactForm.Email" />

    <NvFieldtextarea
        @bind-Value="contactForm.Message"
        Label="Message"
        Rows="5"
        For="() => contactForm.Message" />

    <button type="submit">Send Message</button>
</EditForm>

@code {
    private ContactFormModel contactForm = new();

    public class ContactFormModel
    {
        [Required]
        public string? Name { get; set; }

        [Required]
        [EmailAddress]
        public string? Email { get; set; }

        [Required]
        [MinLength(10)]
        public string? Message { get; set; }
    }
}

Blog Post Editor

razor<EditForm Model="blogPost" OnValidSubmit="PublishPost">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="blogPost.Title"
        Label="Post Title"
        For="() => blogPost.Title" />

    <NvFieldtextarea
        @bind-Value="blogPost.Excerpt"
        Label="Excerpt"
        Rows="3"
        Maxlength="300"
        Description="Brief summary of the post (max 300 characters)"
        For="() => blogPost.Excerpt" />

    <NvFieldtextarea
        @bind-Value="blogPost.Content"
        Label="Content"
        Rows="15"
        Autosize="true"
        For="() => blogPost.Content" />

    <NvFieldtextarea
        @bind-Value="blogPost.Tags"
        Label="Tags"
        Rows="2"
        Description="Comma-separated tags"
        For="() => blogPost.Tags" />

    <button type="submit">Publish Post</button>
</EditForm>

@code {
    private BlogPostModel blogPost = new();

    public class BlogPostModel
    {
        [Required]
        [StringLength(100)]
        public string? Title { get; set; }

        [StringLength(300)]
        public string? Excerpt { get; set; }

        [Required]
        [MinLength(100)]
        public string? Content { get; set; }

        public string? Tags { get; set; }
    }
}

Code Review Comments

razor<EditForm Model="reviewComment" OnValidSubmit="SubmitComment">
    <DataAnnotationsValidator />

    <NvFieldtextarea
        @bind-Value="reviewComment.Comment"
        Label="Review Comment"
        Rows="6"
        Autosize="true"
        Placeholder="Leave your review comments here..."
        For="() => reviewComment.Comment" />

    <div class="comment-options">
        <label>
            <input type="checkbox" @bind="reviewComment.IsBlocking" />
            This is a blocking comment
        </label>
    </div>

    <button type="submit">Submit Comment</button>
</EditForm>

@code {
    private ReviewCommentModel reviewComment = new();

    public class ReviewCommentModel
    {
        [Required]
        [MinLength(10, ErrorMessage = "Comments must be at least 10 characters long")]
        public string? Comment { get; set; }

        public bool IsBlocking { get; set; }
    }
}

This guide covers the most common use cases and patterns for the NvFieldtextarea component in Blazor applications. For more advanced scenarios or specific requirements, refer to the component's API documentation or the Storybook examples.