GVKun编程网logo

在T-SQL中验证日期?(sql验证日期格式不正确)

22

在本文中,我们将为您详细介绍在T-SQL中验证日期?的相关知识,并且为您解答关于sql验证日期格式不正确的疑问,此外,我们还会提供一些关于asp.net–我如何验证日期?、asp.net-mvc–如何

在本文中,我们将为您详细介绍在T-SQL中验证日期?的相关知识,并且为您解答关于sql验证日期格式不正确的疑问,此外,我们还会提供一些关于asp.net – 我如何验证日期?、asp.net-mvc – 如何使用FluentValidation在ClientSide中验证日期?、Java 中验证日期有效性、JavaScript如何验证日期?的有用信息。

本文目录一览:

在T-SQL中验证日期?(sql验证日期格式不正确)

在T-SQL中验证日期?(sql验证日期格式不正确)

我只想验证用户的给定输入

Declare @UserInput NVARCHAR(20)set @UserInput = ''26/07/2013''select ISDATE(@UserInput)

即使日期有效,该日期也将返回false,因为日期为澳大利亚格式

我可以将最后一行更改为以下内容

select isdate(CONVERT(datetime, @UserInput, 103))

它的工作原理。但是,如果@Userinput是垃圾(即:-‘hello’),则最后一条语句将失败。无论用户输入什么内容,我怎样才能得到一个能验证为澳大利亚日期(dd
/ mm / yyyy)的东西?

谢谢

答案1

小编典典

使用 SET DATEFORMAT 指定您希望输入日期的格式:

SET DATEFORMAT DMY;Declare @UserInput NVARCHAR(20)set @UserInput = ''26/07/2013''select ISDATE(@UserInput)

我倾向于在输入到达SQL Server之前执行此类验证,并确保任何日期变量都是日期。

asp.net – 我如何验证日期?

asp.net – 我如何验证日期?

在一个页面中,我采用了一个用于以mm / dd / yyyy formate输入日期的文本框.

我希望当用户输入错误的日期格式时,它会显示一条消息,指出日期格式不正确.

如何验证文本框,用户只能输入正确的日期格式.

提前致谢..

解决方法

使用 DateTime.TryParseExact方法.

DateTime dateValue;

if (DateTime.TryParseExact(textBox.Text,"mm/dd/yyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out dateValue))
{
}

asp.net-mvc – 如何使用FluentValidation在ClientSide中验证日期?

asp.net-mvc – 如何使用FluentValidation在ClientSide中验证日期?

下面的代码工作正常服务器端而不是客户端.为什么?

当我提交表单时,控制权转到BeAValidDate函数以检查日期是否有效.有没有办法验证日期而无需使用Fluent验证进入服务器?

脚本

<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.js" type="text/javascript"></script>

模型

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {
        RuleFor(x => x.FromDate)
            .NotEmpty()
            .WithMessage("Date is required!")
            .Must(BeAValidDate)
            .WithMessage("Invalid Date");
    }

    private bool BeAValidDate(String value)
    {
        DateTime date;
        return DateTime.TryParse(value,out date);
    }
}

调节器

public class PersonController : Controller
{
    public ActionResult Index()
    {
       return View(new Person { FromDate = DateTime.Now.AddDays(2).ToString()});
    }

    [HttpPost]
    public ActionResult Index(Person p)
    {
        return View(p);
    }
}

视图

@using (Html.BeginForm("Index","Person",FormMethod.Post))
{   
    @Html.LabelFor(x => x.FromDate)
    @Html.EditorFor(x => x.FromDate)
    @Html.ValidationMessageFor(x => x.FromDate)

    <input type="submit" name="Submit" value="Submit" />
}

解决方法

使用更大然后或等于验证器的技巧.适合我.

Global.asax – 应用程序启动事件

FluentValidationModelValidatorProvider.Configure(x =>
{
    x.Add(typeof(GreaterThanorEqualValidator),(Metadata,Context,rule,validator) => 
                new LessthanorEqualToFluentValidationPropertyValidator
                (
                    Metadata,validator
                )
            );
});

模型

[Validator(typeof(MyviewmodelValidator))]
public class Myviewmodel
{
    [display(Name = "Start date")]
    [displayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }

    [displayFormat(DataFormatString = "{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)]
    public DateTime DatetoCompareAgainst { get; set; }
}

规则

public class MyviewmodelValidator : AbstractValidator<Myviewmodel>
{
    public MyviewmodelValidator()
    {
        RuleFor(x => x.StartDate)
            .GreaterThanorEqualTo(x => x.DatetoCompareAgainst)
            .WithMessage("Invalid start date");
    }
}

FluentValidationPropertyValidator

public class GreaterThenorEqualTo : FluentValidationPropertyValidator
{
    public GreaterThenorEqualTo(ModelMetadata Metadata,ControllerContext controllerContext,PropertyRule rule,IPropertyValidator validator)
        : base(Metadata,controllerContext,validator)
    {
    }

    public override IEnumerable<ModelClientValidationRule> 
                                                    GetClientValidationRules()
    {
        if (!this.ShouldGenerateClientSideRules())
        {
            yield break;
        }

        var validator = Validator as GreaterThanorEqualValidator;

        var errorMessage = new messageformatter()
            .AppendPropertyName(this.Rule.GetdisplayName())
            .BuildMessage(validator.ErrorMessageSource.GetString());

        var rule = new ModelClientValidationRule{
            ErrorMessage = errorMessage,ValidationType = "greaterthanorequaldate"};
        rule.ValidationParameters["other"] = 
            CompareAttribute.FormatPropertyForClientValidation(
                validator.MemberToCompare.Name);
        yield return rule;
    }
}

控制器动作方法

public ActionResult Index()
{
    var model = new Myviewmodel
    {
        StartDate = DateTime.Now.AddDays(2),DatetoCompareAgainst = default(DateTime)  //Default Date
    };
    return View(model);
}
[HttpPost]
public ActionResult Index(Practise.Areas.FluentVal.Models.Myviewmodel p)
{
    return View(p);
}

视图

@using (Html.BeginForm("Index",FormMethod.Post,new { id = "FormSubmit" }))
{   
    @Html.Hidden("DatetoCompareAgainst",Model.DatetoCompareAgainst);      
    @Html.LabelFor(x => x.StartDate)
    @Html.EditorFor(x => x.StartDate)
    @Html.ValidationMessageFor(x => x.StartDate)
    <button type="submit">
        OK</button>
}

脚本

<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="jquery.validate.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script type="text/javascript">
    (function ($) {
        $.validator.unobtrusive.adapters.add('greaterthanorequaldate',['other'],function (options) {
            var getModelPrefix = function (fieldName) {
                return fieldName.substr(0,fieldName.lastIndexOf(".") + 1);
            };

            var appendModelPrefix = function (value,prefix) {
                if (value.indexOf("*.") === 0) {
                    value = value.replace("*.",prefix);
                }
                return value;
            }

            var prefix          = getModelPrefix(options.element.name),other           = options.params.other,fullOtherName   = appendModelPrefix(other,prefix),element = $(options.form).find(":input[name=" + fullOtherName + 
                                                        "]")[0];

            options.rules['greaterthanorequaldate'] = element;
            if (options.message != null) {
                options.messages['greaterthanorequaldate'] = options.message;
            }
        });
$.validator.addMethod('greaterthanorequaldate',function (value,element,params) {
            var date = new Date(value);
            var datetoCompareAgainst = new Date($(params).val());

            if (isNaN(date.getTime()) || isNaN(datetoCompareAgainst.getTime())) {
                return false;
            }
            return date >= datetoCompareAgainst;
        });

    })(jQuery);
</script>

Java 中验证日期有效性

Java 中验证日期有效性

static int[] DAYS = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };  
  
/** 
 * @param date yyyy-MM-dd HH:mm:ss 
 * @return 
 */  
public static boolean isValidDate(String date) {  
    try {  
        int year = Integer.parseInt(date.substring(0, 4));  
        if (year <= 0)  
            return false;  
        int month = Integer.parseInt(date.substring(5, 7));  
        if (month <= 0 || month > 12)  
            return false;  
        int day = Integer.parseInt(date.substring(8, 10));  
        if (day <= 0 || day > DAYS[month])  
            return false;  
        if (month == 2 && day == 29 && !isGregorianLeapYear(year)) {  
            return false;  
        }  
        int hour = Integer.parseInt(date.substring(11, 13));  
        if (hour < 0 || hour > 23)  
            return false;  
        int minute = Integer.parseInt(date.substring(14, 16));  
        if (minute < 0 || minute > 59)  
            return false;  
        int second = Integer.parseInt(date.substring(17, 19));  
        if (second < 0 || second > 59)  
            return false;  
  
    } catch (Exception e) {  
        e.printStackTrace();  
        return false;  
    }  
    return true;  
}  
public static final boolean isGregorianLeapYear(int year) {  
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);  
}  
public static void main(String[] args) {  
    System.out.println(isValidDate("2100-02-29 23:00:01"));  
}  

JavaScript如何验证日期?

JavaScript如何验证日期?

如何解决JavaScript如何验证日期??

验证日期字符串的一种简单方法是将其转换为日期对象并进行测试,例如

// Expect input as d/m/y

function isValidDate(s) {

  var bits = s.split(''/'');

  var d = new Date(bits[2], bits[1] - 1, bits[0]);

  return d && (d.getMonth() + 1) == bits[1];

}



[''0/10/2017'',''29/2/2016'',''01/02''].forEach(function(s) {

  console.log(s + '' : '' + isValidDate(s))

})

以这种方式测试日期时,仅需要测试月份,因为如果日期超出范围,则月份会更改。如果月份超出范围,则相同。任何年份均有效。

您还可以测试日期字符串的位:

function isValidDate2(s) {

  var bits = s.split(''/'');

  var y = bits[2],

    m = bits[1],

    d = bits[0];

  // Assume not leap year by default (note zero index for Jan)

  var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];



  // If evenly divisible by 4 and not evenly divisible by 100,

  // or is evenly divisible by 400, then a leap year

  if ((!(y % 4) && y % 100) || !(y % 400)) {

    daysInMonth[1] = 29;

  }

  return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]

}



[''0/10/2017'',''29/2/2016'',''01/02''].forEach(function(s) {

  console.log(s + '' : '' + isValidDate2(s))

})

解决方法

我正在尝试测试以确保某个日期有效(如果有人输入2/30/2011则应该是错误的)。

我如何在任何日期都可以这样做?

关于在T-SQL中验证日期?sql验证日期格式不正确的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于asp.net – 我如何验证日期?、asp.net-mvc – 如何使用FluentValidation在ClientSide中验证日期?、Java 中验证日期有效性、JavaScript如何验证日期?等相关知识的信息别忘了在本站进行查找喔。

本文标签: