Ayaz Ali Shah
Ayaz Ali Shah

Reputation: 3531

How to make specific validation for an input using jquery?

I'm trying to validate the input for time 00:00 pm or am. I have done 00:00 with mask() validation, but i'm unable to extend this validation with 00:00 am or pm.

I tried below code for the validation.

$("#phone").mask("00:00");

But i want to give permission to user that put value only in this (00:00 am or pm) format. I would like to appreciate if someone help. Thank you

Upvotes: 0

Views: 127

Answers (3)

Jeric Cruz
Jeric Cruz

Reputation: 1909

you can try to compare it with the value generated by moment.js

function CompareDate(){  
  var inputTime = $("#phone").val();
  var momentx = moment('2016-11-11 ' + inputTime).format('YYYY-MM-DD h:mm A')
  if (momentx == "Invalid date" || !$.trim(inputTime) || inputTime.length == 1) {
    console.log(false);
    //return false;
  }
  else {
    console.log(true);
    //return true;
  }
}
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="phone"/> (e.g. 9:40 PM)
<button onclick="CompareDate();">Compare!</button>

you can add CompareDate() function to your .click() of your submit button.

Upvotes: 0

Star_Man
Star_Man

Reputation: 1091

Try this.

$.mask.rules.H = /(0[0-9]|1[0-2])/;  // 12 hours
$.mask.rules.AP = /[a,A,p,P]M/;//am or pm
$.mask.masks.time = 'H:59 AP';
$("#phone").mask('time');

Upvotes: 0

RonyLoud
RonyLoud

Reputation: 2426

use selector with inputmask to validate the input

$("#phone").inputmask({
    mask: "h:s t\\m",
    placeholder: "hh:mm xm",
    alias: "datetime",
    hourFormat: "12"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/RobinHerbots/Inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>

<input type="text" id="phone"/>

Upvotes: 1

Related Questions