Domanda

Come posso specificare una data personalizzata formiato di essere convalidata con l' La Convalida Del Plugin per jQuery?

È stato utile?

Soluzione

È possibile creare il proprio metodo di convalida personalizzato utilizzando il addMethod funzione. Diciamo che si voleva per validare "dd / mm / aaaa":

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        // put your own logic here, this is just a (crappy) example
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Please enter a date in the format dd/mm/yyyy."
);

E poi sul modulo add:

$('#myForm')
    .validate({
        rules : {
            myDate : {
                australianDate : true
            }
        }
    })
;

Altri suggerimenti

La risposta di nickf è buono, ma nota che il plug-in di convalida include già validatori per diversi altri formati di data, nel file aggiuntivo-methods.js. Prima di scrivere il proprio, assicurarsi che qualcuno non abbia già fatto.

Io personalmente uso l'ottima http://www.datejs.com/ biblioteca.

Docco qui: http://code.google.com/p/datejs/wiki / APIDocumentation

È possibile utilizzare il seguente per ottenere il formato australiano e convaliderà il giorno 29/02/2012 e non salto 29/02/2011:

jQuery.validator.addMethod("australianDate", function(value, element) { 
    return Date.parseExact(value, "d/M/yyyy");
});

$("#myForm").validate({
   rules : {
      birth_date : { australianDate : true }
   }
});

Io uso anche l'input mascherato plugin per standardizzare i dati http://digitalbush.com/ progetti / mascherato-input-plugin /

$("#birth_date").mask("99/99/9999");

Ecco un esempio di un nuovo metodo di validazione che convaliderà quasi tutti i formati data, tra cui:

  • gg / mm / aa o gg / mm / aaaa
  • dd.mm.yy o gg.mm.aaaa
  • dd, mm, aa o gg, mm, aaaa
  • gg mm aa o gg mm aaaa
  • gg-mm-aa o gg-mm-aaaa

Poi, quando si passa il valore al php è possibile convertire con strtotime

Ecco come aggiungere il metodo:

    $.validator.addMethod("anyDate",
    function(value, element) {
        return value.match(/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2])[/., -](19|20)?\d{2}$/);
    },
    "Please enter a date in the format!"
);

Poi si aggiunge il nuovo filtro con:

$('#myForm')
.validate({
    rules : {
        field: {
            anyDate: true
        }
    }
})

;

Ecco un esempio di codice specifico che ha lavorato per me di recente:

// Replace the builtin US date validation with UK date validation
$.validator.addMethod(
    "date",
    function ( value, element ) {
        var bits = value.match( /([0-9]+)/gi ), str;
        if ( ! bits )
            return this.optional(element) || false;
        str = bits[ 1 ] + '/' + bits[ 0 ] + '/' + bits[ 2 ];
        return this.optional(element) || !/Invalid|NaN/.test(new Date( str ));
    },
    "Please enter a date in the format dd/mm/yyyy"
);

Vorrei sottolineare che questo sostituisce in realtà la routine di convalida data di built-in, anche se non ho potuto vedere che questo dovrebbe causare un problema con il plugin corrente.

Ho poi applicato questo al modulo utilizzando:

$( '#my_form input.date' ).rules( 'add', { date: true } );

Questo mi combinazione/modifica post precedenti per raggiungere il mio risultato desiderato:

        // Override built-in date validator
        $.validator.addMethod(
            "date",
            function (value, element) {
                //Return            NB: isRequired is not checked at this stage
                return (value=="")? true : isDate(value);
            },
            "* invalid"
        );

Aggiungere la Data di convalida dopo la convalida di config.I. e.dopo aver richiamato la funzione $(forma).validate({ ...}) metodo.

        //Add date validation (if applicable)
        $('.date', $(frmPanelBtnId)).each(function () {
            $(this).rules('add', {
                date: true
            });
        });

Infine, il principale isDate funzione Javascript modificato per il regno UNITO, Formato della Data

//Validates a date input -- http://jquerybyexample.blogspot.com/2011/12/validate-date-    using-jquery.html
function isDate(txtDate) {
    var currVal = txtDate;
    if (currVal == '')
       return false;

  //Declare Regex  
  var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
  var dtArray = currVal.match(rxDatePattern); // is format OK?

  if (dtArray == null)
      return false;

   //Checks for dd/mm/yyyy format.
   var dtDay = dtArray[1];
   var dtMonth = dtArray[3];
   var dtYear = dtArray[5];

  if (dtMonth < 1 || dtMonth > 12)
      return false;
  else if (dtDay < 1 || dtDay > 31)
      return false;
  else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31)
      return false;
  else if (dtMonth == 2) {
      var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
      if (dtDay > 29 || (dtDay == 29 && !isleap))
          return false;
  }

  return true;
}

Jon, si dispone di alcuni errori di sintassi, vedere qui sotto, questo ha lavorato per me.

  <script type="text/javascript">
$(document).ready(function () {

  $.validator.addMethod(
      "australianDate",
      function (value, element) {
        // put your own logic here, this is just a (crappy) example 
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
      },
      "Please enter a date in the format dd/mm/yyyy"
    );

  $('#testForm').validate({
    rules: {
      "myDate": {
        australianDate: true
      }
    }
  });

});             

$.validator.addMethod("mydate", function (value, element) {

        return this.optional(element) || /^(\d{4})(-|\/)(([0-1]{1})([1-2]{1})|([0]{1})([0-9]{1}))(-|\/)(([0-2]{1})([1-9]{1})|([3]{1})([0-1]{1}))/.test(value);

    });

è possibile inserire come yyyy-mm-dd anche yyyy/mm/dd

, ma non può giudicare le le dimensioni del mese Sometime Febbraio soli 28 o 29 giorni.

@blasteralfred:

Ho seguente regola convalidare data corretta per me (GG MM AAAA)

jQuery.validator.addMethod(
"validDate",
function(value, element) {
    return value.match(/(?:0[1-9]|[12][0-9]|3[01]) (?:0[1-9]|1[0-2]) (?:19|20\d{2})/);
},
"Please enter a valid date in the format DD MM YYYY"

);

Per GG / MM / AAAA

jQuery.validator.addMethod(
"validDate",
function(value, element) {
    return value.match(/(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/);
},
"Please enter a valid date in the format DD/MM/YYYY"

);

Questo non convaliderà 01 13 2017 e 2017/01/13.

E anche non convalida 50 12 2017 e il 50/12/2017.

è facile, Esempio:. Valido per HTML5 tipo automatico = "data"

<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.min.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/localization/messages_es.js"></script>

$(function () {

        // Overload method default "date" jquery.validate.min.js
        $.validator.addMethod(
            "date",
            function(value, element) {
                var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/;
                return value.match(dateReg);
            },
            "Invalid date"
        );

     // Form Demo jquery.validate.min.js
     $('#form-datos').validate({
        submitHandler: function(form) {
            form.submit();
        }
    });

});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top