Disable zero as first letter in <input>

前端 未结 7 1321
無奈伤痛
無奈伤痛 2021-02-08 19:51

Below code disables 0 as the first character in #foo.
However, you can bypass this by typing 123, then drag to select 123

7条回答
  •  生来不讨喜
    2021-02-08 20:12

    You could add a "submit" event to validate whether it's entered or not, regardless of how it could have gotten there:

    $( "form" ).submit(function( event ) {
      if ( $( "input:first" ).val() != 0 ) {
        $( "span" ).text( "Validated..." ).show();
        return;
      }
      $( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
      event.preventDefault();
    });
    
    
    
    

    Type 'Anything but 0' to validate.

    jQuery's working is example is last on page here (https://api.jquery.com/submit/)

    NOTE: The most important part will be to add the "event.preventDefault()" action, because that will keep the form from accidentally submitting.

提交回复
热议问题