2

I want to check the length of input string and validate it.If its greater than length the show message beside the text box.I my case the length is 10

<div>
  <input type="text" name="ref_code" id="ref_code" value="" onchange="checkCodeStatus()" size=18>

  <div id="msg" style="margin-left: 15px;"></div>
</div> 
 <script type="text/javascript">
    function checkCodeStatus(){
     var ref_code = $("#ref_code").val();
    $.ajax({
    type:'post',
    url:'<?php echo site_url('mypage/check_code/'); ?>',
    data:{ref_code: ref_code},
    success:function(msg){
             if(msg.indexOf('value does exist') > -1)
                 $('#msg').html('<span style="color: green;">'+msg+"</span>");    
             else $('#msg').html('<sapn style="color:red;">Value does not exist</span>');
         }
});
}

                        </script>

3 Answers 3

1

Use .length to check input string's length and if it is more than 10 just set the value of div with id msg. And then return so function does not run anymore.

if(ref_code.length >10) {
  $("#msg").val("Some error message");
  return;
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are two ways to do one by html you just allow max length for example

<input type="text" name="usrname" maxlength="10">

or also you can do this by using jquery

var ref_code = $("#ref_code").val();
var refLength = ref_code.length;

if(refLength >10) {
    $("#msg").html("your message");
    return;
}

2 Comments

It works but while user is inputting the string he must not allowed to enter more tha 10 letters and the error message should be shown. @ Muhammad Usman
@nishu then you can use jquery for this there are two solutions
0

Check the length of input using .length

var ref_code = $("#ref_code").val();
if (ref_code.length > 10) {
     $('#msg').text('Your error text will go here');
     return false;
}

Also you should make a separate .js file to keep js code. Embed in html is not a good practice.For <?php echo site_url; ?> line you can keep your site url inside js file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.