0

I have a problem, that I'm struggling with since 2 days. I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:

    $("#start").click(function(){ // click func
    if ($.trim($('#phonenr').val()) == ''){
     $("#error").show();

I tried adding:

     if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)

But it just won't work. Any help would be appreciated. Also please tell me how can I make it allow only numbers?

Thank you!

Final code, with help of @Saumya Rastogi. $("#start").click(function(){

    var reg = /^\d+$/;
    var input_str = $('#phonenr').val();
   chopped_str = input_str.substring(0, input_str.length - 1);
   if(!reg.test(input_str)) {
    $("#error").show();
    return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
  $("#error").show();
} else {
unkn0wnx
  • 137
  • 3
  • 14

3 Answers3

1

If you are using HTML5, then you can make use of the new number input type available

<input type="number" name="phone" min="10" max="10">

You can also use the pattern attribute to restrict the input to a specific Regular expression.

Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
  • Thanks a lot for your reply. I tried using HTML5, but the action depends on Java and a message stored in the javascript file, in order to display the error saying that the phone number is invalid. – unkn0wnx Dec 23 '16 at 15:00
1

You can make your validation work.

You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:

$(function() {
 $('#btn').on('click',function(e) {
   var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
    var input_str = $('#phonenr').val();
    chopped_str = input_str.substring(0, input_str.length - 1);
    if(!reg.test(input_str)) {
     $('label.error').show();
        return;
    }
    if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
      $('label.error').show();
    } else {
      $('label.error').hide();
    }
  });
})
label.error {
  display: none;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • I tried modifying the line that I need from the whole snippet, and it didn't work... I got this: if ($.trim($('#phonenr').val()) == '') && || ($.trim($('#phonenr').length < 15)). – unkn0wnx Dec 23 '16 at 15:31
  • According to your condition the operator `&&` will only show the error message if the input box is empty & if the input box has less than 15 characters, due to this the error will not been shown! You should tell me what type of validation you want? – Saumya Rastogi Dec 23 '16 at 15:34
  • let me kind of show you what I'm talking about.. $("#start").click(function(){// click function if ($.trim($('#phonenr').val()) == '') [AND / OR] *PHNR_FROM_INPUT* <(less than) 15 [AND / OR] *CONTAINS SOMETHING ELSE THAN NUMBERS* { $("#error").show(); } – unkn0wnx Dec 23 '16 at 15:38
  • @unkn0wnx - I've updated the code, I've added validate button, let me know in case of you want anything else! – Saumya Rastogi Dec 23 '16 at 15:40
  • Awesome, I modified it and it's working, minimum length is 15! One more thing, how can I add a validation for NUMBERS_ONLY? Thanks so much, here's how it is modified: $("#start").click(function(){ var reg = /^\d+$/; var input_str = $('#phonenr').val(); chopped_str = input_str.substring(0, input_str.length - 1); if(!reg.test(input_str)) { $(this).val(chopped_str); } if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) { $("#error").show(); – unkn0wnx Dec 23 '16 at 15:48
  • I did, it is the correct answer indeed. Just if you can help me add a only numbers validation it would be great. Thanks again! – unkn0wnx Dec 23 '16 at 15:50
  • For validation of numbers, just check out my answer, I am checking for regex expression, if the `test` method returns `false` then you should show the error message, its that simple! – Saumya Rastogi Dec 23 '16 at 15:50
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/131364/discussion-between-unkn0wnx-and-saumya-rastogi). – unkn0wnx Dec 23 '16 at 15:52
  • Why not just make the regular expression specify the min and max amount of digits that are acceptable and then your code can be reduced to two lines? Also, this doesn't account for someone bypassing the button and submitting the form by pressing ENTER. – Scott Marcus Dec 23 '16 at 16:23
0

If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:

// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){

  // Get DOM references:
  var theForm = document.querySelector("#frmTest");
  var thePhone = document.querySelector("#txtPhone");
  var btnSubmit = document.querySelector("#btnSubmit");
  
  // Hook into desired events. Here, we'll validate as text is inputted
  // into the text field, when the submit button is clicked and when the 
  // form is submitted
  theForm.addEventListener("submit", validate);
  btnSubmit.addEventListener("click", validate);
  thePhone.addEventListener("input", validate);
  
  // The simple validation function
  function validate(evt){
    var errorMessage = "Not a valid phone number!";
    
    // Just check the input against a regular expression
    // This one expects 10 digits in a row.
    // If the pattern is matched the form is allowed to submit,
    // if not, the error message appears and the form doesn't submit.
    !thePhone.value.match(/\d{3}\d{3}\d{4}/) ? 
      thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = ""; 
      evt.preventDefault();
  }
 
});
span {
  background: #ff0;
}
<form id="frmTest" action="#" method="post">
  <input id="txtPhone" name="txtPhone"><span></span>
  <br>
  <input type="submit" id="btnSubmit">
</form>

Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.

Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.

<form id="frmTest" action="#" method="post">
  <input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
         placeholder="555-555-5555" title="555-555-5555"
         pattern="\d{3}-\d{3}-\d{4}" required>
  <input type="submit" id="btnSubmit">
</form> 

Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • It still doesn't work because the click on the element is actioned by javascript and not html5. – unkn0wnx Dec 23 '16 at 15:34
  • Not sure what you are trying to say here. It certainly does work. HTML5 is not just tags and attributes. It's actually new elements, attributes AND JavaScript APIs. Yes, of course handling events is done with JavaScript. But the actual checking of the phone number against the regular expression specified in the `pattern` attribute is done natively by the browser with nothing more than a plain attribute. The JavaScript is used (in this case) solely for displaying the custom error message you said you wanted. – Scott Marcus Dec 23 '16 at 15:36
  • I have added the exact pattern you gave me, and then I entered only 1 number (1 character) in the input tab, and it didn't work... – unkn0wnx Dec 23 '16 at 15:39
  • @unkn0wnx Have you tried the Fiddle I linked to? This does exactly what you said you wanted. What browser are you testing in? – Scott Marcus Dec 23 '16 at 15:39
  • Marcus, I cannot edit my javascript code more than what I have posted on this thread. I have to use the same code or else the javascript file won't load. – unkn0wnx Dec 23 '16 at 15:42
  • I need to somehow modify my line that I already got and add just a length and number check. – unkn0wnx Dec 23 '16 at 15:42
  • I really don't understand your requirements. You say that just your line can be adjusted, but you've accepted an answer that is much more than just your line and rejected my answer which is asking you to do the same thing. – Scott Marcus Dec 23 '16 at 16:15