2

我想做服务器端验证,以确保每个带有“必需”类的文本框都不为空。我可以在 jQuery 中做到这一点没问题,但在 C# 中还不是专业人士。这是我得到的:

protected void BtnCatering_Click(object sender, EventArgs e)
{
    if (TextBox.CssClass == "required" && TextBox.Text == "")
    {
        MessageBox.Show("Please fill in required fields");
    }
}

<p>
    <label for="BookingName">Booking Name <span>*</span></label>
    <asp:TextBox class="inputText required" ID="BookingName" runat="server" />
</p>
<p>
    <label for="ArrivaltDate">Arrival Date<span>*</span></label>
    <asp:TextBox CssClass="myDatepicker inputText required" id="ArrivaltDate" runat="server" />
</p
4

4 回答 4

1

试试这个方法。

protected void BtnCatering_Click(object sender, EventArgs e)
{
    if (BookingName.Attributes["class"].ToString().Contains("required") && BookingName.Text == "")
    {
        MessageBox.Show("Please fill in required fields");
    }
}

//BookingName是您的文本框 ID。

于 2013-08-19T15:55:18.740 回答
1

出于这个原因,ASP.NETValidation Controls可以用来验证服务器端的数据(也可以选择在客户端)。

您可以将RequiredFieldValidator控件与每个文本框或CustomValidator控件一起使用。

请参阅MSDN:ASP.NET 服务器控件的验证类型

例如,对于TextBox具有 ID 的控件,BookingName您可以使用以下内容。

<asp:RequiredFieldValidator EnableClientScript="False" ID="RequiredFieldValidator1" ControlToValidate="BookingName" runat="server" ErrorMessage="Please fill in this field"></asp:RequiredFieldValidator>

如果您使用Visual Studio这些控件,则在您的工具箱中。

于 2013-08-19T15:53:04.573 回答
1

像这样的东西可能是你的解决方案:

var results = this.Controls.OfType<TextBox>().Where(c =>
    Convert.ToString(c.Attributes["class"]).Contains("required"));

然后您可以遍历该结果集。也许是这样的:

foreach (var tb in results)
{
    if (string.IsNullOrEmpty(tb.Text))
    {
        // do something here because this TextBox is empty
    }
}

但是,更正确的方法是可能RequiredFieldValidator对每个控件使用 ,这样您就可以在准备好时调用this.Validate()Page然后检查并this.IsValid对其Page做出反应。

于 2013-08-19T15:53:31.460 回答
0

代码很简单:

if (CssUtils.HasClass(TextBox.CssClass, "required") && TextBox.Text == "") {
    ..do stuff..
}

但这当然假设您有一个有效的CssUtils类,可以准确地检测到类的存在。

public static class CssUtils
{
    /// <summary>
    /// http://dev.w3.org/html5/spec/common-microsyntaxes.html#space-character
    /// </summary>
    private static readonly char[] WhitespaceCharacters = new[] { ' ', '\t', '\n', '\f', '\r' };

    /// <summary>
    /// ToggleAggregator toggles the <paramref name="parsedClass"/> within the <paramref name="current"/> classes.
    /// </summary>
    /// <param name="current">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="parsedClass">
    /// A class to toggle within the <paramref name="current"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    private static string ToggleAggregator(string current, string parsedClass)
    {
        return HasClass(current, parsedClass)
                   ? RemoveClass(current, parsedClass)
                   : AddClass(current, parsedClass);
    }

    /// <summary>
    /// AddClass adds the provided <paramref name="classes"/> to the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to add to the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of merged classes.
    /// </returns>
    public static string AddClass(string source, string classes)
    {
        var sourceClasses = ParseClasses(source);
        var parsedClasses = ParseClasses(classes);
        var mergedClasses =
            sourceClasses
                .Union(parsedClasses)
                .ToArray()
                .Join(" ");
        return mergedClasses;
    }

    /// <summary>
    /// AddClass adds the provided <paramref name="classes"/> to the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// An <see cref="Array.string"/> of classes to add to the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of merged classes.
    /// </returns>
    public static string AddClass(string source, params string[] classes)
    {
        return AddClass(source, classes.Join(" "));
    }

    /// <summary>
    /// HasClass checks whether all of the provided <paramref name="classes"/> are contained in the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to check in the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// <c>True</c> if all of the <paramref name="classes"/> are contained in the <paramref name="source"/> classes, <c>False</c> otherwise.
    /// </returns>
    public static bool HasClass(string source, string classes)
    {
        if (source.IsEmpty() || classes.IsEmpty()) return false;
        var sourceClasses = ParseClasses(source);
        var parsedClasses = ParseClasses(classes);
        return parsedClasses.Intersect(sourceClasses).Count() == parsedClasses.Count();
    }

    /// <summary>
    /// RemoveClass removes the provided <paramref name="classes"/> from the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to remove from the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of remaining classes.
    /// </returns>
    public static string RemoveClass(string source, string classes)
    {
        var sourceClasses = ParseClasses(source);
        var parsedClasses = ParseClasses(classes);
        var resultClasses =
            sourceClasses
                .Except(parsedClasses)
                .ToArray()
                .Join(" ");
        return resultClasses;
    }

    /// <summary>
    /// RemoveClass removes the provided <paramref name="classes"/> from the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// An <see cref="Array.string"/> of classes to remove from the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of remaining classes.
    /// </returns>
    public static string RemoveClass(string source, params string[] classes)
    {
        return RemoveClass(source, classes.Join(" "));
    }

    /// <summary>
    /// ToggleClass toggles the provided <paramref name="classes"/> within the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to toggle within the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    public static string ToggleClass(string source, string classes)
    {
        var parsedClasses = ParseClasses(classes);
        return parsedClasses.Aggregate(source ?? "", ToggleAggregator);
    }

    /// <summary>
    /// ToggleClass toggles the provided <paramref name="classes"/> within the <paramref name="source"/> classes.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// An <see cref="Array.string"/> of classes to toggle within the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    public static string ToggleClass(string source, params string[] classes)
    {
        return ToggleClass(source, classes.Join(" "));
    }

    /// <summary>
    /// ToggleClass toggles the provided <paramref name="classes"/> within the <paramref name="source"/> classes dependant on the state of the <paramref name="switch"/>.
    /// </summary>
    /// <param name="source">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes to toggle within the <paramref name="source"/> classes.
    /// </param>
    /// <param name="switch">
    /// When <c>True</c>, the <paramref name="classes"/> will be added to the <paramref name="source"/> classes.
    /// When <c>False</c>, the <paramref name="classes"/> will be removed from the <paramref name="source"/> classes.
    /// </param>
    /// <returns>
    /// The <see cref="String"/> of resultant classes.
    /// </returns>
    public static string ToggleClass(string source, string classes, bool @switch)
    {
        return @switch ? AddClass(source, classes) : RemoveClass(source, classes);
    }

    /// <summary>
    /// ParseClasses splits the provided whitespace separated list of <paramref name="classes"/> into an array of distinct classes.
    /// </summary>
    /// <param name="classes">
    /// A <see cref="String"/> of whitespace separated classes.
    /// </param>
    /// <returns>
    /// A <see cref="Array.string"/> of distinct classes.
    /// </returns>
    public static string[] ParseClasses(string classes)
    {
        return (classes ?? "")
            .Split(WhitespaceCharacters, StringSplitOptions.RemoveEmptyEntries)
            .Distinct()
            .ToArray();
    }
}
于 2013-08-19T16:03:23.620 回答