1

Working on a sample reactjs form. It has two date fields, startdate and enddate as shown below

<input type="text" name="startdate" value={this.state.startDate}/>
<input type="text" name="enddate" value={this.state.endDate}/>

these two fields should allow date, only in "dd/mm/yyyy" format and should not allow any other characters expect valid date, month, year and "/".

How to allow only the valid characters as mentioned above using javascript?

MemoryLeak
  • 485
  • 3
  • 8
  • 20
  • Possible duplicate of [How to properly validate input values with React.JS?](http://stackoverflow.com/questions/24019431/how-to-properly-validate-input-values-with-react-js) – stdob-- Oct 24 '16 at 06:24
  • @stdob my problem is not specific to reactjs, it about input field date format validation. if you can provide a link to fix the issue, it will be helpful. I searched but I didn't find one. – MemoryLeak Oct 24 '16 at 06:30

3 Answers3

1

If working only on a text field, use momentJS to parse the field content and assert the format.

There is node-dateformat too (I never tried this last one).

A second approach would be to use a datepicker like:

Damien Leroux
  • 11,177
  • 7
  • 43
  • 57
  • it s a text field which should allow the date in "dd/mm/yyyy" format....no date picker or jquery allowed...want to fix this using javascript – MemoryLeak Oct 24 '16 at 06:41
  • So momentJs should do the job. I used it to parse text field that was not filled as experted. With momentJs, you can declare a format and assrt the text field value is correct – Damien Leroux Oct 24 '16 at 06:46
  • I don't want to use any other js library. I want to handle this on keypress, which should allow only valid characters. for example, if my first text is 7 then it should to allow only "/" character, any other number to 7 will be an invalid date. – MemoryLeak Oct 24 '16 at 06:54
  • hum ok, in that case use `str.charAt(str.length - 1)` to get the last caractere of the textdfield value and verify it is fitting a number of a `/` (with a [regexp](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/RegExp)). Gook luck :) – Damien Leroux Oct 24 '16 at 07:01
0

You can add onchange on input field and use the preg_match from this link

Community
  • 1
  • 1
Lionel Dcosta
  • 177
  • 1
  • 2
  • 13
0

In case if anyone using redux and redux-form, there is a mechanism Field Normalizing Check out details at redux-form

FazalRasel
  • 56
  • 5