C# 資料驗證

來源:互聯網
上載者:User
#region  驗證
/// <summary>
/// 驗證所修改或添加的資訊是否已經存在,針對資料庫表中唯一欄位
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="keyName">欄位名</param>
/// <param name="key">值</param>
/// <returns>true:已經存在;false:不存在</returns>
private bool isExist(string tableName, string keyName, string key)
{
    string sql = "select * from " + tableName + " where " + keyName + "='" + key + "'";
    DataTable dt = new DataTable();
    try
    {
        //執行SQL得到DataTable
        //......
        if (dt.Rows.Count > 0)
            return true;
        else
            return false;
    }
    catch(Exception ex)
    {
        throw new Exception(ex.Message);
    }
    finally
    {
        db.Close();
    }
}
/// <summary>
/// 匹配由字母、數字、底線、漢字組成的字串
/// </summary>
/// <param name="str">進行匹配的字串</param>
/// <returns>true:匹配成功;false:匹配失敗</returns>
private bool regexCommonString(string str)
{
    Regex exStr = new Regex(@"^[\da-zA-Z_\u4e00-\u9fa5]+$");
    if (exStr.Match(str).Success)
        return true;
    else
        return false;
}
/// <summary>
/// 匹配數字字串
/// </summary>
/// <param name="str">進行匹配的字串</param>
/// <returns>true:匹配成功;false:匹配失敗</returns>
private bool regexNumberString(string str)
{
    Regex exStr = new Regex(@"^-?[0-9]*\.?[0-9]+$");
    if (exStr.Match(str).Success)
        return true;
    else
        return false;
}
/// <summary>
/// 匹配數字、字母組成的字串
/// </summary>
/// <param name="str">進行匹配的字串</param>
/// <returns>true:匹配成功;false:匹配失敗</returns>
private bool regexNumberLetterString(string str)
{
    Regex exStr = new Regex(@"^[\da-zA-Z]+$");
    if (exStr.Match(str).Success)
        return true;
    else
        return false;
}
/// <summary>
/// 匹配字母組成的字串
/// </summary>
/// <param name="str">進行匹配的字串</param>
/// <returns>true:匹配成功;false:匹配失敗</returns>
private bool regexLetterString(string str)
{
    Regex exStr = new Regex(@"^[a-zA-Z]+$");
    if (exStr.Match(str).Success)
        return true;
    else
        return false;
}

/// <summary>

/// 匹配正整數的字串
/// </summary>
/// <param name="str">進行匹配的字串</param>
/// <returns>true:匹配成功;false:匹配失敗</returns>
public static bool regexPlusNumberString(string str)
{
    Regex exStr = new Regex(@"^\d+$");
    if (exStr.Match(str).Success)
        return true;
    else
        return false;
}

#endregion

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.