ttmt
ttmt

Reputation: 4984

Check only numbers used in input field

I have a simple if statment in a verify function that check at least 10 numbers are used in a field

function verfiyFields() {
    var flag = true;

    var number = $atj('#interested-number-form');


    if(number.val().replace(/\s+/g, '').length < 10){
        number.parent().prepend('<p class="form-error">Please enter phone number</p>');
        fadeOut();
        flag = false;
    }

    return flag;
}

How can I also check that only numbers are used.

Upvotes: 2

Views: 153

Answers (2)

Sean Wessell
Sean Wessell

Reputation: 3510

function verfiyFields() {
  var reg = /^\D*(?:\d\D*){10}$/;
  var number = $atj('#interested-number-form');

  var flag = reg.test(number.val())

  if (!(flag)) {
    number.parent().append('<p class="form-error">Please enter a valid 10 digit phone number</p>');
  }

  return flag;
}

Use RegExp.test(str) to check to make sure that the length of the field excluding all characters that are not digits is 10. RegExp.test returns a true or false value so this can be the flag you return.

RegExp.test(str) Documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

Demo: http://jsfiddle.net/SeanWessell/1v6vnath/

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 241008

You could use .match(/^\d+$/) to check if there are only digits.

var value = number.val().replace(/\s+/g, '');
if (value.length >= 10 && value.match(/^\d+$/)) {
  // ..
}

You can also check if there are at least 10 digits using the regular expression /^\d{10,}$/ and avoid checking the length property:

var value = number.val().replace(/\s+/g, '')
if (value.match(/^\d{10,}$/)) {
  // ..
}

As a side note, you can also use the pattern attribute:

<form>
  <input type="text" pattern="^\d{10,}$" />
  <input type="submit" />
</form>

Upvotes: 3

Related Questions