gpt4 book ai didi

c# - 如果和/或施工不工作

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:34 25 4
gpt4 key购买 nike

请看下面的代码,在最后一个 IF 语句中,我尝试了“&&”或“||”的不同组合但如果两个格式 bool 值都设置为 true,则只能在此示例中获得有效输入。我尝试以任何其他方式编写 IF 语句,要么验证总是返回错误,要么验证规则停止应用。

private static readonly Regex regexSSNDashes = new Regex(@"^\d{3}[-]\d{2}[-]\d{4}$");
private static readonly Regex regexSSNNoDashes = new Regex(@"^\d{3}\d{2}\d{4}$");

public static string SSN(String propertyName, bool isRequired, bool allowDashFormat, bool allowNoDashFormat)
{
if ((String.IsNullOrWhiteSpace(propertyName))
&& (isRequired == true))
{
return "SSN required.";
}

if ((!String.IsNullOrEmpty(propertyName))
&& ((!regex.SSNDashes.IsMatch(propertyName)) && (allowDashFormat == true))
&& ((!regex.SSNNoDashes.IsMatch(propertyName)) && (allowNoDashFormat == true)))
{
return "Invalid SSN.";
}

return null;
}

根据下面的答案和反馈,这里是完整的代码,它运行良好,并且可以通过编写更多 Regex 语句(我将来可能会添加 EIN)或编写不同的字符串来检查是否可以接受不同的电话格式来轻松扩展信用卡等

using System;
using System.Text.RegularExpressions;

public class ValidationRules
{
// SSN Rules
// Format 123-45-6789
private static readonly Regex regexSSNDashes = new Regex(@"^\d{3}[-]\d{2}[-]\d{4}$");
// Format 123456789
private static readonly Regex regexSSNNoDashes = new Regex(@"^\d{3}\d{2}\d{4}$");

/// <summary>
/// Get error string if property is not in the specified formats.
/// </summary>
/// <param name="propertyName">The property being validated.</param>
/// <param name="isRequired">Bool value if the property is required to be filled else may be null</param>
/// <param name="allowDashFormat">Bool value if format 123-45-6789 is allowed.</param>
/// <param name="allowNoDashFormat">Bool value if format 123456789 is allowed.</param>
/// <returns>Returns custom string for error type specified if error exists, else returns null.</returns>
public static string SSN(String propertyName, bool isRequired,
bool allowDashFormat, bool allowNoDashFormat)
{
if (isRequired && String.IsNullOrWhiteSpace(propertyName))
{
return "SSN required.";
}

if (!String.IsNullOrEmpty(propertyName) &&
!(allowDashFormat && regexSSNDashes.IsMatch(propertyName)) &&
!(allowNoDashFormat && regexSSNNoDashes.IsMatch(propertyName)))
{
return "Invalid SSN.";
}

return null;
}
}

最佳答案

虽然接受的答案在技术上是正确的,但让我们问一下哪个更易于维护,这个:

if (!String.IsNullOrEmpty(propertyName) &&
!(regex.SSNDashes.IsMatch(propertyName) && allowDashFormat) &&
!(regex.SSNNoDashes.IsMatch(propertyName) && allowNoDashFormat))
{
return "Invalid SSN.";
}

或者这个:

//You've already checked for a null string, it doesn't need to be repeated here
if (allowDashFormat)
{
if (!regex.SSNDashes.IsMatch(propertyName))
return "Invalid SSN";
}
else
{
if (!regex.SSNNoDashes.IsMatch(propertyName))
return "Invalid SSN";
}

重点不是为了使事情简短而使事情复杂化。编译器将为您处理。编写可维护/可读的代码,而不是短代码。

关于c# - 如果和/或施工不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49578362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com