NvFieldnumber Component - Practical Guide for Blazor Developers
The NvFieldnumber component is a Blazor wrapper around Nova's number input component, providing seamless integration with Blazor's data binding, forms, and validation systems. It includes built-in stepper buttons for incrementing/decrementing values.
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 number input-specific features and patterns.
Basic Usage
Simple Number Input
<NvFieldnumber Label="Quantity" Placeholder="Enter quantity" />
Number Input with Description
<NvFieldnumber
Label="Age"
Description="Enter your age in years"
Placeholder="25" />
Two-Way Data Binding
The component supports Blazor's @bind-Value syntax for seamless two-way data binding with nullable double values:
Simple Binding
@code {
private double? quantity = 1;
}
<NvFieldnumber
@bind-Value="quantity"
Label="Quantity"
Min="1"
Max="100" />
<p>Selected quantity: @quantity</p>
Multiple Number Fields with Binding
@code {
private double? price = 29.99;
private double? discount = 0;
private double? taxRate = 8.25;
}
<NvFieldnumber
@bind-Value="price"
Label="Price ($)"
Min="0"
Step="0.01"
Placeholder="0.00" />
<NvFieldnumber
@bind-Value="discount"
Label="Discount (%)"
Min="0"
Max="100"
Step="0.1"
Placeholder="0.0" />
<NvFieldnumber
@bind-Value="taxRate"
Label="Tax Rate (%)"
Min="0"
Max="50"
Step="0.25"
Placeholder="8.25" />
<div class="calculation">
<p>Subtotal: $@price</p>
<p>Discount: @discount%</p>
<p>Tax: @taxRate%</p>
<p>Total: $@(CalculateTotal(price ?? 0, discount ?? 0, taxRate ?? 0))</p>
</div>
@code {
private double CalculateTotal(double price, double discount, double taxRate)
{
var discountedPrice = price * (1 - discount / 100);
var taxAmount = discountedPrice * (taxRate / 100);
return Math.Round(discountedPrice + taxAmount, 2);
}
}
Event Handling
Using ValueChanged Event
<NvFieldnumber
Label="Rating"
Min="1"
Max="5"
Step="1"
ValueChanged="OnRatingChanged" />
<div class="rating-display">
@for (int i = 1; i <= 5; i++)
{
<span class="@(i <= (currentRating ?? 0) ? "star filled" : "star")">★</span>
}
</div>
@code {
private double? currentRating = 3;
private void OnRatingChanged(double? value)
{
currentRating = value;
Console.WriteLine($"Rating changed to: {value}");
}
}
Event with Binding
@code {
private double? amount = 0;
private void OnAmountChanged(double? value)
{
amount = value;
// Perform additional calculations or validation
UpdateCalculations(value ?? 0);
}
}
<NvFieldnumber
Value="amount"
Label="Amount"
Min="0"
Step="0.01"
ValueChanged="OnAmountChanged" />
<p>Amount with tax (8.25%): $@(Math.Round((amount ?? 0) * 1.0825, 2))</p>
@code {
private void UpdateCalculations(double value)
{
// Additional calculation logic here
}
}
Stepper Controls and Ranges
Basic Stepper
<NvFieldnumber
@bind-Value="count"
Label="Count"
Min="0"
Max="10"
Step="1" />
Decimal Stepper
<NvFieldnumber
@bind-Value="weight"
Label="Weight (kg)"
Min="0"
Max="500"
Step="0.1"
Placeholder="70.5" />
Currency Input
<NvFieldnumber
@bind-Value="price"
Label="Price ($)"
Min="0"
Step="0.01"
Placeholder="29.99" />
Currency Input with Icon Slot
Use slots to add currency icons for better visual representation:
<NvFieldnumber
@bind-Value="usdPrice"
Label="Price (USD)"
Min="0"
Step="0.01"
Placeholder="0.00">
<PrefixSlot>
<NvIcon Name="dollar" Size="SizeEnum.sm" />
</PrefixSlot>
</NvFieldnumber>
<NvFieldnumber
@bind-Value="eurPrice"
Label="Price (EUR)"
Min="0"
Step="0.01"
Placeholder="0.00">
<PrefixSlot>
<NvIcon Name="euro" Size="SizeEnum.sm" />
</PrefixSlot>
</NvFieldnumber>
<NvFieldnumber
@bind-Value="percentage"
Label="Discount"
Min="0"
Max="100"
Step="0.1"
Placeholder="0.0">
<SuffixSlot>
<NvIcon Name="percent" Size="SizeEnum.sm" />
</SuffixSlot>
</NvFieldnumber>
@code {
private double? usdPrice = 0;
private double? eurPrice = 0;
private double? percentage = 0;
}
Form Integration
The component integrates seamlessly with Blazor's EditForm for validation and form submission:
Basic Form Integration
<EditForm Model="productModel" OnValidSubmit="SaveProduct">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="productModel.Name"
Label="Product Name"
For="() => productModel.Name" />
<NvFieldnumber
@bind-Value="productModel.Quantity"
Label="Quantity"
Min="1"
Max="1000"
For="() => productModel.Quantity" />
<NvFieldnumber
@bind-Value="productModel.Price"
Label="Price ($)"
Min="0.01"
Step="0.01"
For="() => productModel.Price" />
<button type="submit">Save Product</button>
</EditForm>
@code {
private ProductModel productModel = new();
private void SaveProduct()
{
// Process product save
Console.WriteLine("Product saved successfully!");
}
public class ProductModel
{
[Required]
public string? Name { get; set; }
[Required]
[Range(1, 1000, ErrorMessage = "Quantity must be between 1 and 1000")]
public double? Quantity { get; set; }
[Required]
[Range(0.01, double.MaxValue, ErrorMessage = "Price must be greater than 0")]
public double? Price { get; set; }
}
}
Validation
Range Validation
<EditForm Model="settingsModel" OnValidSubmit="SaveSettings">
<DataAnnotationsValidator />
<NvFieldnumber
@bind-Value="settingsModel.FontSize"
Label="Font Size (px)"
Min="8"
Max="72"
Step="1"
For="() => settingsModel.FontSize" />
<NvFieldnumber
@bind-Value="settingsModel.Timeout"
Label="Timeout (seconds)"
Min="5"
Max="300"
Step="5"
For="() => settingsModel.Timeout" />
<button type="submit">Save Settings</button>
</EditForm>
@code {
private SettingsModel settingsModel = new() { FontSize = 14, Timeout = 30 };
public class SettingsModel
{
[Required]
[Range(8, 72, ErrorMessage = "Font size must be between 8 and 72 pixels")]
public double? FontSize { get; set; }
[Required]
[Range(5, 300, ErrorMessage = "Timeout must be between 5 and 300 seconds")]
public double? Timeout { get; set; }
}
}
Required Field Validation
<EditForm Model="measurementModel" OnValidSubmit="RecordMeasurement">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="measurementModel.SampleId"
Label="Sample ID"
For="() => measurementModel.SampleId" />
<NvFieldnumber
@bind-Value="measurementModel.Value"
Label="Measurement Value"
Required="true"
Min="0"
Step="0.001"
For="() => measurementModel.Value" />
<NvFieldtext
@bind-Value="measurementModel.Units"
Label="Units"
For="() => measurementModel.Units" />
<button type="submit">Record Measurement</button>
</EditForm>
@code {
private MeasurementModel measurementModel = new();
public class MeasurementModel
{
[Required]
public string? SampleId { get; set; }
[Required(ErrorMessage = "Measurement value is required")]
public double? Value { get; set; }
[Required]
public string? Units { get; set; }
}
}
Custom Validation
<EditForm Model="budgetModel" OnValidSubmit="SubmitBudget">
<DataAnnotationsValidator />
<NvFieldnumber
@bind-Value="budgetModel.Income"
Label="Monthly Income ($)"
Min="0"
Step="100"
For="() => budgetModel.Income" />
<NvFieldnumber
@bind-Value="budgetModel.Expenses"
Label="Monthly Expenses ($)"
Min="0"
Step="50"
For="() => budgetModel.Expenses" />
<NvFieldnumber
@bind-Value="budgetModel.Savings"
Label="Monthly Savings ($)"
Min="0"
Step="25"
For="() => budgetModel.Savings" />
<button type="submit">Calculate Budget</button>
</EditForm>
@code {
private BudgetModel budgetModel = new();
public class BudgetModel
{
[Required]
[BudgetValidation]
public double? Income { get; set; }
[Required]
[BudgetValidation]
public double? Expenses { get; set; }
[Required]
[BudgetValidation]
public double? Savings { get; set; }
}
public class BudgetValidationAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
var budget = (BudgetModel)validationContext.ObjectInstance;
var number = value as double?;
if (number < 0)
return new ValidationResult("Value cannot be negative");
// Additional budget-specific validation could go here
if (budget.Income.HasValue && budget.Expenses.HasValue && budget.Savings.HasValue)
{
if (budget.Expenses + budget.Savings > budget.Income)
return new ValidationResult("Expenses and savings cannot exceed income");
}
return ValidationResult.Success;
}
}
}
Advanced Scenarios
Dynamic Calculations
<NvFieldnumber
@bind-Value="length"
Label="Length"
Min="0"
Step="0.1"
ValueChanged="CalculateArea"
Placeholder="10.5" />
<NvFieldnumber
@bind-Value="width"
Label="Width"
Min="0"
Step="0.1"
ValueChanged="CalculateArea"
Placeholder="5.2" />
<div class="result">
<h4>Calculated Area</h4>
<p>@area square units</p>
@if (area > 100)
{
<p class="warning">Large area detected!</p>
}
</div>
@code {
private double? length = 0;
private double? width = 0;
private double area = 0;
private void CalculateArea(double? value)
{
if (length.HasValue && width.HasValue)
{
area = Math.Round((length.Value * width.Value), 2);
}
}
}
Percentage Calculator
<NvFieldnumber
@bind-Value="totalAmount"
Label="Total Amount ($)"
Min="0"
Step="0.01"
ValueChanged="CalculatePercentages"
Placeholder="100.00" />
<NvFieldnumber
@bind-Value="percentage"
Label="Percentage (%)"
Min="0"
Max="100"
Step="0.1"
ValueChanged="CalculateResult"
Placeholder="15.0" />
<div class="calculation">
<p>Result: $@result</p>
<p>Formula: @totalAmount × (@percentage / 100) = @result</p>
</div>
@code {
private double? totalAmount = 0;
private double? percentage = 0;
private double result = 0;
private void CalculatePercentages(double? value)
{
CalculateResult(value);
}
private void CalculateResult(double? value)
{
if (totalAmount.HasValue && percentage.HasValue)
{
result = Math.Round((totalAmount.Value * percentage.Value / 100), 2);
}
}
}
Unit Converter
<div class="converter">
<div class="input-section">
<NvFieldnumber
@bind-Value="celsius"
Label="Celsius (°C)"
Step="0.1"
ValueChanged="ConvertToFahrenheit"
Placeholder="20.0" />
<span class="equals">=</span>
<NvFieldnumber
@bind-Value="fahrenheit"
Label="Fahrenheit (°F)"
Step="0.1"
ValueChanged="ConvertToCelsius"
Placeholder="68.0" />
</div>
<div class="input-section">
<NvFieldnumber
@bind-Value="meters"
Label="Meters (m)"
Min="0"
Step="0.01"
ValueChanged="ConvertToFeet"
Placeholder="1.00" />
<span class="equals">=</span>
<NvFieldnumber
@bind-Value="feet"
Label="Feet (ft)"
Min="0"
Step="0.01"
ValueChanged="ConvertToMeters"
Placeholder="3.28" />
</div>
</div>
@code {
private double? celsius = 0;
private double? fahrenheit = 32;
private double? meters = 0;
private double? feet = 0;
private void ConvertToFahrenheit(double? value)
{
if (value.HasValue)
{
fahrenheit = Math.Round((value.Value * 9 / 5) + 32, 1);
}
}
private void ConvertToCelsius(double? value)
{
if (value.HasValue)
{
celsius = Math.Round((value.Value - 32) * 5 / 9, 1);
}
}
private void ConvertToFeet(double? value)
{
if (value.HasValue)
{
feet = Math.Round(value.Value * 3.28084, 2);
}
}
private void ConvertToMeters(double? value)
{
if (value.HasValue)
{
meters = Math.Round(value.Value / 3.28084, 2);
}
}
}
Survey with Numeric Scales
<EditForm Model="surveyModel" OnValidSubmit="SubmitSurvey">
<DataAnnotationsValidator />
<div class="survey-question">
<label>How satisfied are you with our service?</label>
<div class="scale">
<span>1 (Very Dissatisfied)</span>
<NvFieldnumber
@bind-Value="surveyModel.Satisfaction"
Min="1"
Max="5"
Step="1"
For="() => surveyModel.Satisfaction" />
<span>5 (Very Satisfied)</span>
</div>
</div>
<div class="survey-question">
<label>How likely are you to recommend us?</label>
<div class="scale">
<span>0 (Not at all likely)</span>
<NvFieldnumber
@bind-Value="surveyModel.Recommendation"
Min="0"
Max="10"
Step="1"
For="() => surveyModel.Recommendation" />
<span>10 (Extremely likely)</span>
</div>
</div>
<button type="submit">Submit Survey</button>
</EditForm>
@code {
private SurveyModel surveyModel = new();
public class SurveyModel
{
[Required]
[Range(1, 5, ErrorMessage = "Satisfaction rating must be between 1 and 5")]
public double? Satisfaction { get; set; }
[Required]
[Range(0, 10, ErrorMessage = "Recommendation score must be between 0 and 10")]
public double? Recommendation { get; set; }
}
}
Best Practices
- Set appropriate min/max values to prevent invalid inputs
- Use meaningful step values based on the data type (1 for integers, 0.01 for currency, etc.)
- Always provide clear labels explaining what the number represents
- Use descriptions to clarify units or expected ranges
- Consider decimal precision for financial or measurement data
- Implement range validation using data annotations
- Handle nullable values appropriately in calculations
- Consider mobile users when setting step sizes
Common Patterns
Product Configuration
<EditForm Model="productConfig" OnValidSubmit="AddToCart">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="productConfig.Name"
Label="Product Name"
For="() => productConfig.Name" />
<NvFieldnumber
@bind-Value="productConfig.Quantity"
Label="Quantity"
Min="1"
Max="99"
For="() => productConfig.Quantity" />
<NvFieldnumber
@bind-Value="productConfig.UnitPrice"
Label="Unit Price ($)"
Min="0.01"
Step="0.01"
For="() => productConfig.UnitPrice" />
<div class="total">
Total: $@(Math.Round(((productConfig.Quantity ?? 0) * (productConfig.UnitPrice ?? 0)), 2))
</div>
<button type="submit">Add to Cart</button>
</EditForm>
@code {
private ProductConfigModel productConfig = new() { Quantity = 1 };
public class ProductConfigModel
{
[Required]
public string? Name { get; set; }
[Required]
[Range(1, 99)]
public double? Quantity { get; set; }
[Required]
[Range(0.01, double.MaxValue)]
public double? UnitPrice { get; set; }
}
}
Settings Panel
<EditForm Model="appSettings" OnValidSubmit="SaveSettings">
<DataAnnotationsValidator />
<NvFieldnumber
@bind-Value="appSettings.FontSize"
Label="Font Size (px)"
Min="10"
Max="24"
Step="1"
For="() => appSettings.FontSize" />
<NvFieldnumber
@bind-Value="appSettings.AnimationDuration"
Label="Animation Duration (ms)"
Min="100"
Max="2000"
Step="50"
For="() => appSettings.AnimationDuration" />
<NvFieldnumber
@bind-Value="appSettings.MaxResults"
Label="Max Search Results"
Min="10"
Max="100"
Step="5"
For="() => appSettings.MaxResults" />
<button type="submit">Save Settings</button>
</EditForm>
@code {
private AppSettingsModel appSettings = new() { FontSize = 14, AnimationDuration = 300, MaxResults = 25 };
public class AppSettingsModel
{
[Required]
[Range(10, 24)]
public double? FontSize { get; set; }
[Required]
[Range(100, 2000)]
public double? AnimationDuration { get; set; }
[Required]
[Range(10, 100)]
public double? MaxResults { get; set; }
}
}
Financial Calculator
<div class="calculator">
<NvFieldnumber
@bind-Value="principal"
Label="Principal Amount ($)"
Min="0"
Step="100"
ValueChanged="CalculatePayment"
For="() => principal" />
<NvFieldnumber
@bind-Value="interestRate"
Label="Annual Interest Rate (%)"
Min="0"
Max="30"
Step="0.1"
ValueChanged="CalculatePayment"
For="() => interestRate" />
<NvFieldnumber
@bind-Value="loanTerm"
Label="Loan Term (years)"
Min="1"
Max="30"
Step="1"
ValueChanged="CalculatePayment"
For="() => loanTerm" />
<div class="result">
<h4>Monthly Payment</h4>
<p class="amount">$@monthlyPayment</p>
</div>
</div>
@code {
private double? principal = 100000;
private double? interestRate = 4.5;
private double? loanTerm = 30;
private string monthlyPayment = "0.00";
private void CalculatePayment(double? value)
{
if (principal.HasValue && interestRate.HasValue && loanTerm.HasValue)
{
var monthlyRate = interestRate.Value / 100 / 12;
var numPayments = loanTerm.Value * 12;
if (monthlyRate == 0)
{
monthlyPayment = (principal.Value / numPayments).ToString("F2");
}
else
{
var payment = principal.Value * (monthlyRate * Math.Pow(1 + monthlyRate, numPayments)) /
(Math.Pow(1 + monthlyRate, numPayments) - 1);
monthlyPayment = payment.ToString("F2");
}
}
}
}
This guide covers the most common use cases and patterns for the NvFieldnumber component in Blazor applications. For more advanced scenarios or specific requirements, refer to the component's API documentation or the Storybook examples.