0_0
0_0

Reputation: 537

Regex for 'attr=value' style input

So I have to get an input value in attr=value format. Something like name=John or surname=Doe. The string could contain number but no symbol other then = is allowed. Now, I need to validate the field in Javascript. I have already got a regex, which goes something like this /[a-zA-Z0-9]+[=]+[a-zA-Z0-9]+/. Its working fine. However, I feel like there might be a better regex to do this. Also, if user inputs something like name=John-, it allows it. Which should not be the case. If you guys could point me to the right direction, it would be great.

var regexField = $('#regex-test'),
    RegEx = /[a-zA-Z0-9]+[=]+[a-zA-Z0-9]+/,
    isValid = function(element){
      return RegEx.test(element.val());
    };
$('#submit').click(function(e){
  if(isValid(regexField)){
    $('#err').hide();
    return;
  }
  $('#err').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="err" style="display:none">
    Please enter proper value!
</div>
<input type="text" id="regex-test" required/>
<button id="submit">Submit</button>

Upvotes: 0

Views: 99

Answers (2)

Xophmeister
Xophmeister

Reputation: 9211

Your expression is not far off from what you want. The reason it's allowing name=John- is because there is no anchoring to the ends of the string. It will also accept, for example, #$%name=John-!?foo. To anchor to the start use ^ and $ for the end.

You don't need to put the = in a character class (as you've only got one option); and you definitely don't want to quantify it with + as you want exactly one (not one or more).

Finally, you can simplify it a little bit by making it case-insensitive, using the i flag.

Ultimately, this gives you:

/^[a-z0-9]+=[a-z0-9]+$/i

You can make it even simpler if you allow underscores in your attributes and values: then you can change [a-z0-9] to \w...but that's your call :)

Upvotes: 3

Paul Roub
Paul Roub

Reputation: 36438

A version that allows whitespace around the =, and allows only whitespace after the name=value portion (and so disallows symbols at the end), would be:

RegEx = /\s*[a-z0-9]+\s*=\s*[a-z0-9]+\s*$/i

var regexField = $('#regex-test'),
    RegEx = /\s*[a-z0-9]+\s*=\s*[a-z0-9]+\s*$/i,
    isValid = function(element){
      return RegEx.test(element.val());
    };
$('#submit').click(function(e){
  if(isValid(regexField)){
    $('#err').hide();
    return;
  }
  $('#err').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="err" style="display:none">
    Please enter proper value!
</div>
<input type="text" id="regex-test" required/>
<button id="submit">Submit</button>

Upvotes: 0

Related Questions