开发者

Javascript check for spaces

I have this function but I want to check for spaces only in the front and back, not in the middle before i sent back what can i do with it...

func开发者_如何学运维tion validateNumeric() {
  var val = document.getElementById("tbNumber").value;
  var validChars = '0123456789.'; 

  for(var i = 0; i < val.length; i++){ 
    if(validChars.indexOf(val.charAt(i)) == -1){
    alert('Please enter valid number');
    return false; 
    } 
  }
  return true; 
  }


Time for regular expressions.

function startsOrEndsWithWhitespace(str)
{
    return /^\s|\s$/.test(str);
}

Tests:

> /^\s|\s$/.test('123454')
  false
> /^\s|\s$/.test('123 454')
  false
> /^\s|\s$/.test(' 123454')
  true
> /^\s|\s$/.test(' 123454 ')
  true
> /^\s|\s$/.test('123454 ')
  true

if i dont wanna accept 1 1 what do i have to change

function containsWhitespace(str)
{
    return /\s/.test(str);
}

Tests:

> /\s/.test('123454')
  false
> /\s/.test('123 454')
  true
> /\s/.test(' 123454')
  true
> /\s/.test('123454 ')
  true
> /\s/.test(' 123454 ')
  true
> /\s/.test(' 123 454 ')
  true


For a really simple solution, if you can use jQuery, use jQuery.trim() and compare the trimmed string with the original. If not equal, then there were spaces so the number is invalid.


function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
} 

source


To trim your string you can write something like this, as it's been said before:

function trim(str){
    return str.replace(/^\s+|\s+$/g), '');
}

But why bother?
Want you really want is:

function validateNumeric(str) {
    return !isNaN(parseFloat(str));
}

Note your original code accepts something like "..." or "7.8..9" as being numeric, which is wrong.

Update: kennebec has called my attention to the fact that parseFloat() will ignore trailing garbage at the end of string. So I call your attention to this alternative given in an answer to question "Validate numbers in JavaScript - IsNumeric()":

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

(Original credit goes to CMS).


function validateNumeric() {
  var val = document.getElementById("tbNumber").value;
  if (!/^\s*(?:\d+(?:\.\d*)?|\.\d+)\s*$/.test(val)) {
    alert('Please enter a valid number');
    return false; 
  }
  return true;
}

(?:\d+(?:\.\d*)|\.\d+) breaks down as follows:

  1. \d+ is any number of digits, e.g. 123
  2. (\.\d*)? optionally matches a fraction, e.g. .25 and . or blank but not .1.2
  3. \.\d+ matches a fraction without an integer part as in .5 but not 1.5.
  4. (?:abc|def) groups things together and matches either abc or def

/^\s*(?:\d+(?:\.\d*)|\.\d+)\s*$/ means any number of spaces followed by one or more decimal digits followed by any number of spaces. So it does what your validChars loop did plus allows spaces at the start and end.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜