blankface
blankface

Reputation: 6347

Regex pattern for preventing leading whitespace in HTML input

<input type="text" pattern="^[a-zA-Z1-9].*">

How can I restrict the following input element from having leading whitespace, ie, it should always start with a character except a whitespace.

This answer suggested I use pattern="^[a-zA-Z1-9].*" but it doesn't seem to work.

EDIT:

It works only if I wrap it in a form tag and a submit button. Clicking the button triggers the error. But I want to be able to restrict users from entering whitespace on the input box itself.

Upvotes: 0

Views: 801

Answers (3)

Gowtham
Gowtham

Reputation: 1597

The Following Regex mentioned in question Works without wrapping inside form tag

input[type="text"]:valid{
background:green;
}
input[type="text"]:invalid{
background:red;
}
<input type="text" pattern="^[a-zA-Z1-9].*">

Upvotes: 0

wp78de
wp78de

Reputation: 18970

To achieve this without a form-tag we can use a JavaScript live input filter like this:

var noLeadingSpace = /^\w.*$/;

$("input")
  .data("oldValue", "")
  .bind("input propertychange", function() {
    var $this = $(this);
    var newValue = $this.val();

    if (!noLeadingSpace.test(newValue))
        return $this.val($this.data("oldValue"));

    return $this.data("oldValue", newValue);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

Upvotes: 1

Jan Ciołek
Jan Ciołek

Reputation: 1816

It does work, but it will be validated if you try to send a form.

function myValidator(v){
  var input = document.getElementById('uglyWay')
  
  if(input){
    input.value = input.value.replace(/ /g, '')
  }
}
<form>
<input id="uglyWay" oninput='myValidator()' type="text" pattern="^[a-zA-Z1-9].*">
<button type="submit">Send</button>
</form>

Upvotes: 0

Related Questions