JSFiddle - React, Tailwind, and code Playground
by OriginalEXE
HTML
<form id="forma">
<label>Telefon:<input type="text" name="broj" /></label>
<label>JMBG:<input type="text" name="jmbg" /></label>
<button type="submit">Submit</button>
</form>
CSS
form label {
display: block;
}
form input[type="text"] {
border: 1px solid #666;
}
form input[type="text"].error {
border-color: red;
}
JavaScript
var forma = $( '#forma' );
forma.on( 'keyup change', 'input[type="text"]', function() {
var $this = $( this ),
name = $this.attr( 'name' ),
value = $this.val();
switch ( name ) {
case ( 'broj' ) :
case ( 'jmbg' ) :
value = value.replace( /[^\d\.]/g, '' );
$this.val( value ).removeClass( 'error' );
break;
}
});
forma.on( 'change', 'input[type="text"]', function() {
var $this = $( this ),
name = $this.attr( 'name' ),
value = $this.val();
switch ( name ) {
case ( 'broj' ) :
value = value.replace( /[^\d\.]/g, '' );
if ( value.length > 10 ) {
$this.addClass( 'error' );
}
break;
case ( 'jmbg' ) :
value = value.replace( /[^\d\.]/g, '' );
if ( 13 !== value.length ) {
$this.addClass( 'error' );
abort = true;
}
break;
}
});
forma.on( 'click', 'button[type="submit"]', function() {
var abort = false;
forma.find( 'input[type="text"]' ).each( function() {
var $this = $( this ),
name = $this.attr( 'name' ),
value = $this.val();
switch ( name ) {
case ( 'broj' ) :
value = value.replace( /[^\d\.]/g, '' );
if ( value.length > 10 ) {
$this.addClass( 'error' );
abort = true;
}
break;
case ( 'jmbg' ) :
...